  Delphi ԵݿУDBGrid ʾݵҪֶ֮һ DBGrid ȱʡδԵõȱ⡣ʵȫǵĳͨﵽDBGrid ۵Ŀġ̣ͨǿԸı DBGrid ıͷߵǰɫͱɫԼصĴСͷ
    µʾʾ˶ DBGrid Եãʹ Delphi ʾıҳеıһƯۡ
    ʾУ
     Form1 Ϸ DBGrid1Query1DataSource1 ݿصԣʹ DBGrid1 ʾеݡȻ DBGrid1  onDrawColumnCell ¼м´룬Ȼг򣬾ͿԿĽˡ Windows98Delphi5.0 µͨ
procedure TMainForm.DBGrid1DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn;State: TGridDrawState);
var i :integer;
begin
  if gdSelected in State then Exit;
//ͷͱɫ
    for i :=0 to (Sender as TDBGrid).Columns.Count-1 do
    begin
      (Sender as TDBGrid).Columns[i].Title.Font.Name :=''; //
      (Sender as TDBGrid).Columns[i].Title.Font.Size :=9; //С
      (Sender as TDBGrid).Columns[i].Title.Font.Color :=$000000ff; //ɫ(ɫ)
      (Sender as TDBGrid).Columns[i].Title.Color :=$0000ff00; //ɫ(ɫ)
    end;
//иı񱳾ɫ
  if Query1.RecNo mod 2 = 0 then
    (Sender as TDBGrid).Canvas.Brush.Color := clInfoBk //屳ɫ
  else
    (Sender as TDBGrid).Canvas.Brush.Color := RGB(191, 255, 223); //屳ɫ
//ߵɫ
    DBGrid1.DefaultDrawColumnCell(Rect,DataCol,Column,State);
  with (Sender as TDBGrid).Canvas do // cell ı߿
  begin
    Pen.Color := $00ff0000; //廭ɫ(ɫ)
    MoveTo(Rect.Left, Rect.Bottom); //ʶλ
    LineTo(Rect.Right, Rect.Bottom); //ɫĺ
    Pen.Color := $0000ff00; //廭ɫ(ɫ)
    MoveTo(Rect.Right, Rect.Top); //ʶλ
    LineTo(Rect.Right, Rect.Bottom); //ɫ
  end;
end; 

  
ԭ취ûDevExpress֮ǰ....
һ½ӵ 

 : Delphi5 - иıDBGridɫ 
    Form1 Ϸ DBGrid1Query1DataSource1 ݿصԣʹ DBGrid1 ʾеݡȻ DBGrid1  onDrawColumnCell ¼м´룬Ȼг

:
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
 DataCol: Integer; Column: TColumn; State: TGridDrawState);

var i:integer;
begin
  if gdSelected in State then Exit;  //иı񱳾ɫ 
    if adoQuery1.RecNo mod 2 = 0 then
      (Sender as TDBGrid).Canvas.Brush.Color := clinfobk //屳ɫ
  else
    (Sender as TDBGrid).Canvas.Brush.Color := RGB(191, 255, 223);  //屳ɫ

  //ߵɫ
  DBGrid1.DefaultDrawColumnCell(Rect,DataCol,Column,State);
  with (Sender as TDBGrid).Canvas do // cell ı߿
  begin
    Pen.Color := $00ff0000; //廭ɫ(ɫ)
    MoveTo(Rect.Left, Rect.Bottom); //ʶλ
    LineTo(Rect.Right, Rect.Bottom); //ɫĺ
    Pen.Color := clbtnface; //廭ɫ(ɫ)
    MoveTo(Rect.Right, Rect.Top); //ʶλ
    LineTo(Rect.Right, Rect.Bottom); //ɫ
  end;
end;

BDEеtable1δͨɫûиб仯  

 
 2003-11-11 17:12:09    DelphiDBGridв 
   Delphiṩ˹ǿ DBGridԷݿӦóơǽDBGridÿһý㣨Gridֻһ򵥵ı༭򣬲ûݡDelphiҲṩһЩû룬DBComboBoxDBCheckBoxЩȴûDBGridǿDelphiܲVisual FoxproDBGridлýԷûأʵǿͨDBGridвʵһ㡣

    DelphiDBGridڲƣϸһDBEditݵʵǸDBEditδýطͼˡԣDBGridвϸһκӼ򵥵DbCheckBoxӵĶԻ򣬶DBGridв롣һDBGridвDBComboBoxĲ裬ͬİ취Բ

  1Delphi 4.0½һĿ

  2ֱ϶Data AccessDataSourceTableData ControlsDBGridDBComboBoxĸForm1ϡ

  3ø£

rcf1  趨ֲ
Form1 Caption 'DBGridвSpinEditʾ'
DataSource1 DataSet Table1
Table1 DatabaseName DBDEMOS
TableName 'teacher.DBF'
Active True
DBGrid1 DataSource DataSource1
DBComboBox1 DataField SEX
DataSource DataSource1
Visible False
Strings Items. ''| 'Ů'

ע⣺Teacher.dbfǷӳְԱֻǡСǡŮ

  4DrawDataCell¼ǻƵԪ񣬵ýӦֶϿӦֶһʱƶϿ򵽻ýϣʹϿӣӶﵽDBGridָʾDBComboBoxĹܡDBGrid1OnDrawDataCell¼£

procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState);
begin
  if (gdFocused in State) then
  begin
    if (Field.FieldName = DBComboBox1.DataField ) then
    begin
      DBComboBox1.Left := Rect.Left + DBGrid1.Left;
      DBComboBox1.Top := Rect.Top + DBGrid1.top;
      DBComboBox1.Width := Rect.Right - Rect.Left;
      DBComboBox1.Height := Rect.Bottom - Rect.Top;
      DBComboBox1.Visible := True;
    end;
  end;
end;

  5DBGridָԪδýʱʾDBComboBoxDBGrid1OnColExit¼£
procedure TForm1.DBGrid1ColExit(Sender: TObject);
begin
  If DBGrid1.SelectedField.FieldName = DBComboBox1.DataField then
    begin
      DBComboBox1.Visible := false;
    end;
end;

  6DBGridָлýʱDrawDataCell¼ֻǻƵԪ񣬲ʾDBComboBoxDBComboBoxûлý㣬ݵ뻹ڵԪϽСDBGrid1KeyPress¼еSendMessage Windows API봫䵽DBComboBoxϣӶﵽDBComboBoxϽ롣˻ҪKeyPress¼£

procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
  if (key < > chr(9)) then
  begin
    if (DBGrid1.SelectedField.FieldName =DBComboBox1.DataField) then
    begin
      DBComboBox1.SetFocus;
      SendMessage(DBComboBox1.HandleWM_Charword(Key)0);
    end;
  end;
end;

    Windows 98Delphi 4.015 µͨϣʹԸӷݵĿݿӦó  

 
 2003-11-11 17:17:56    DBGridߵ 
   ʹ Delphi3 ݿ̵ʱϣ DBGRID ʾݵʱFoxPro  BROWSE һָļвйӦʲôʵ֣

    ֪ Delphi  TStringGrid һ FixedCols ָСȻTDBGrid ֱʹһԣͨǿתҲһܣΪ඼ TCustomGrid ࡣ Delphi 3.0 Demos\Db\CtrlGrid Ϊ˵÷ӵ TFmCtrlGrid.FormShow мһУ 

    TStringGrid(DbGrid1).FixedCols := 2; 

    иóƶʱSymbol вƶַҲԲķ Form ּ

    type TMyGrid = Class(TDBGrid) end; 

    Ȼ TFmCtrlGrid.FormShow м룺 

    TMyGrid(DbGrid1).FixedCols := 2; 

    ߴʽвͬʵʶһġ FixedCols Ϊ 2Ϊ DBGrid иָʾУ㽫 DBGrid  Options Ե dgIndicator ΪFalseӦ FixedCols Ϊ1  

 
 2003-11-11 17:21:36    ʹdbgridĳϱɫ 
    DBGrid Ԫ DrawDataCell ¼ϵıӻֵɫ.
 :

OnDrawDataCell(...)
begin
  with TDBGrid(Sender) do
  begin
    if () then
      Canvas.TextOut(Rect.Left + 4
    Rect.Top + 2

'Ҫʾ');
end;

    ῴ DBGrid ʾصΪԭDBGridҪʾ TextOut ʾص
     :
     Query Ԫλ(ԪϰҼ Add Fields...ѡ)ڲҪʾϵλ OnGetText ¼һ趨Ϊ False;

procedure TForm1.Query1Detail1GetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
  //  DBGrid ֪ʱҪҪʾõFalse -> ʾ
  // Ϳɱ TextOut ص
  DisplayText : = False;
end;
end;

     Delphi 3 ܼ.:ԱĳֶεֵС0ʱΪΪ.
 DBGrid.OnDrawColumnCell(...) :

begin
  if TableField.AsInteger < 0 then
    DBGrid.Canvas.Font.Color := clRed
  else
    DBGrid.Canvas.Font.Color := clBlack;
  DBGrid.DefaultDrawColumnCell(...);
end;

 Field ָĸʽԾЧд.  

 
 2003-11-11 17:25:29    ʵսDelphiɫЧ 
   Delphiеؼ(TDbGrid)ʾͱ༭ݿдʮҪãȻʹؼͬʱҲΪдݲ֣ۻҡؼԣ˷ĴأĴӸıɫýǶȣһֽ취

    Ϊؼ6Чʵַؼݼӵķԡ

1. ЧʵкżзֱԲͬɫʾڵС
file://DbGridDrawColumnCell¼бд´룺

Case DataCol Mod 2 = 0 of
True: DbGrid1.Canvas.Brush.Color:= clBlue; file://żɫ
False: DbGrid1.Canvas.Brush.Color:= clAqua; file://ǳɫ
End;
DbGrid1.Canvas.Pen.Mode:=pmMask;
DbGrid1.DefaultDrawColumnCell (Rect
DataCol
Column
State);

2. ߣͬʱԺɫͻʾǰԪЧͻʾǰѡеֶΡ

file://޸Ϊ
Case DataCol Mod 2 = 0 of
True: DbGrid1.Canvas.Brush.Color:= clBlue; file://żɫ
False: DbGrid1.Canvas.Brush.Color:= clAqua; file://ǳɫ
End;
If ((State = [gdSelected]) or (State=[gdSelectedgdFocused])) then
If Not DbGrid1.SelectedRows.CurrentRowSelected then
DbGrid1.Canvas.Brush.Color:=clRed; file://ǰѡеԪʾɫ
DbGrid1.Canvas.Pen.Mode:=pmMask;
DbGrid1.DefaultDrawColumnCell (Rect 
DataCol 
Column 
State);

ַͻеʾЧ

3ԺɫͻʾǰѡеС
    DbGridؼOptionsеdgRowSelectΪ棬ColorΪclAqua(ɫ)
DbGridDrawColumnCell¼бд´룺

if ((State = [gdSelected]) or (State=[gdSelected gdFocused])) then
DbGrid1.Canvas.Brush.color:=clRed; file://ǰԺɫʾʹñǳɫ
DbGrid1.Canvas.pen.mode:=pmmask;
DbGrid1.DefaultDrawColumnCell (Rect
DataCol
Column
State);

4ͻԵİЧͻǰУֲͬУֶΣ

file://ͬ3޸Ϊ
if ((State = [gdSelected]) or (State=[gdSelectedgdFocused])) then
begin
Case DataCol Mod 2 = 0 of
True : DbGrid1.Canvas.Brush.color:=clRed; file://ǰѡеżʾɫ
False: DbGrid1.Canvas.Brush.color:=clblue; file://ǰѡеʾɫ
end;
DbGrid1.Canvas.pen.mode:=pmmask;
DbGrid1.DefaultDrawColumnCell (Rect
DataCol
Column
State);
end;

5ߣ ͬʱԺɫͻԵǰЧ

file://ͬ3޸Ϊ
Case Table1.RecNo mod 2 = 0 of file://ݼļ¼Žж
True : DbGrid1.Canvas.Brush.color:=clAqua; file://żǳɫʾ
False: DbGrid1.Canvas.Brush.color:=clblue; file://ɫʾ
end;
if ((State = [gdSelected]) or (State=[gdSelectedgdFocused])) then file://ѡúɫʾ
DbGrid1.Canvas.Brush.color:=clRed;
DbGrid1.Canvas.pen.mode:=pmMask;
DbGrid1.DefaultDrawColumnCell (Rect
DataCol
Column
State);

6˫Чмòͬɫ֣ͬʱѡЧֲͬС

file://ͬ3޸Ϊ
Case Table1.RecNo mod 2 = 0 of file://ݼļ¼Žж
True : DbGrid1.Canvas.Brush.color:=clAqua; file://żǳɫʾ
False: DbGrid1.Canvas.Brush.color:= clblue; file://ɫʾ
end;
If ((State = [gdSelected]) or (State=[gdSelectedgdFocused])) then
Case DataCol mod 2 = 0 of
True : DbGrid1.Canvas.Brush.color:=clRed; file://ǰѡеżúɫ
False: DbGrid1.Canvas.Brush.color:= clGreen; file://ǰѡеɫʾ
end;
DbGrid1.Canvas.pen.mode:=pmMask;
DbGrid1.DefaultDrawColumnCell (Rect
DataCol
Column
State);

    6ֱַؼкеɫʽã߿ԸԼҪЧóDelphi5вͨ  

 
 2003-11-13 11:11:31    DBGridTitleԲѯ 
ؼ:DBGrid   

    ʵֵDBGridTitleԲѯһͨó򣬲һһ飬粻SQLOrder by ...ΪSQLԭѾOrder by ...ҵһTitleʱҪĿԴ

procedure TFHkdata.SortQuery(Column:TColumn);
var
  SqlStr,myFieldName,TempStr: string;
  OrderPos: integer;
  SavedParams: TParams;
begin
  if not (Column.Field.FieldKind in [fkData,fkLookup]) then exit;
  if Column.Field.FieldKind =fkData then
    myFieldName := UpperCase(Column.Field.FieldName)
  else
    myFieldName := UpperCase(Column.Field.KeyFields);
  while Pos(myFieldName,';')<>0 do
  myFieldName := copy(myFieldName,1,Pos(myFieldName,';')-1)+ ',' + copy(myFieldName,Pos(myFieldName,';')+1,100);
  with TQuery(TDBGrid(Column.Grid).DataSource.DataSet) do
  begin
    SqlStr := UpperCase(Sql.Text);
    // if pos(myFieldName,SqlStr)=0 then exit;
    if ParamCount>0 then
    begin
      SavedParams := TParams.Create;
      SavedParams.Assign(Params);
    end;
    OrderPos := pos('ORDER',SqlStr);
    if (OrderPos=0) or (pos(myFieldName,copy(SqlStr,OrderPos,100))=0) then
      TempStr := ' Order By ' + myFieldName + ' Asc'
    else if pos('ASC',SqlStr)=0 then
      TempStr := ' Order By ' + myFieldName + ' Asc'
    else
      TempStr := ' Order By ' + myFieldName + ' Desc';
    if OrderPos<>0 then SqlStr := Copy(SqlStr,1,OrderPos-1);
    SqlStr := SqlStr + TempStr;
    Active := False;
    Sql.Clear;
    Sql.Text := SqlStr;
    if ParamCount>0 then
    begin
      Params.AssignValues(SavedParams);
      SavedParams.Free;
    end;
    Prepare;
    Open;
  end;
end;
  

 
 2003-11-13 11:13:57    ȥDbGridԶӹ 

ؼ:DbGrid  

    ƶһ¼ʱٰһ¡¡ͻ׷һ¼ȥ 
    procedure TForm1.DataSource1Change(Sender: TObject; Field: TField);
    begin
      if TDataSource(Sender).DataSet.Eof then TDataSource(Sender).DataSet.Cancel;
    end;
 
 
  

 
 2003-11-16 12:05:46    DBGrid֧ƶĽ(л wangxian11 ṩ) 
Լ׽WM_MOUSEWHEELϢ
private
  OldGridWnd : TWndMethod;
procedure NewGridWnd (var Message : TMessage);
public

procedure TForm1.NewGridWnd(var Message: TMessage);
var
  IsNeg : Boolean;
begin
  if Message.Msg = WM_MOUSEWHEEL then
  begin
    IsNeg := Short(Message.WParamHi) < 0;
    if IsNeg then
      DBGrid1.DataSource.DataSet.MoveBy(1)
    else
      DBGrid1.DataSource.DataSet.MoveBy(-1)
  end
  else
    OldGridWnd(Message);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  OldGridWnd := DBGrid1.WindowProc ;
  DBGrid1.WindowProc := NewGridWnd;
end;      

 
 2003-11-17 14:46:56    dbgridƶ㵽ָк 
   dbgridǴTCustomGrid̳ģcolrowԣֻprotectedģֱӷʣҪһ£

    TDrawGrid(dbgrid1).row:=row;
    TDrawGrid(dbgrid1).col:=col;
    dbgrid1.setfocus;
ͿԿЧˡ

    1 ǾģDBGridڲĻңΪDBGrid޷λǰ¼DBGridֻҲͰˣֻǻһЩ⣬ԭֻܵѡļ¼ڿԳֶѡȵȣԼȥԣDBGridɱ༭ͿɴˣΪǰ¼Ĺϵĵֶκܿܲе
    2 ҳõĽ취ǽϳΪcolǰȫģûһ⣩

    Query1.first;
    TDrawGrid(dbgrid1).col:=1;
    dbgrid1.setfocus;

    ýƵһеһе 

 
 2003-11-17 14:55:26    ʹDBGRIDɫ˸еֵı仯仯 
   ʱʱΪͻʾݵĸԣ߹СȣҪͨıɫľе˵

    ʹDBGRIDɫ˸еֵı仯仯<60Ϊɫ
    DelphiݿƹDBGridӳݱҪҲõĹӦóУԲɫķʽʾDBGridԣʾһЩҪĻҪʾʱԸıЩڵлеǰͱɫ
DBGridDefaultDrawingCell񣩵ĻơDefaultDrawingȱʡΪTrue˼DelphiʹDBGridȱʡƷݣǰضӵTfieldDisplayFormatEditFormatƵģDBGridDefaultDrawingóFalseDelphiͲݣTDBGridOnDrawDataCell¼ṩԼĻ̣Իܣ
ｫõDBGridһҪԣCanvasܶ๹һԡCanvas˵ǰʾDBGridı棬жʾݺͷָDBGridCanvasDBGridCanvasֵĻʾӦʱ漰CanvasBrushԺFillRectTextOutBrushԹ涨DBGrid.CanvasʾͼɫԼWindows GDI FillRectʹõǰBrush򣬷TextOutCanvasıݡ

һϸ˵ʾɫDBGridҪһDBGridһɫɸѡSpinEdit⻹ColorGridѡݵԪǰͱɫ

1.ΪColorDBGridProject䴰Form1η蹹ΪӦֵУ

 Table1 DatabaseName: DBDEMOS
     TableName: EMPLOYEE.DB
     Active: True;
 DataSource1 DataSet: Table1
 DBGrid1 DataSource1: DataSource1
     DefaultDrawing: False
 SpinEdit1 Increment:200
     Value: 20000
 ColorGrid1 GridOrdering: go161

2.ΪDBGrid1OnDrawDataCell¼дӦ

//дĳ<60ΪɫĿմ
procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;Field: TField; State: TGridDrawState);
begin
 if Table1.Fieldbyname(Salary).value<=SpinEdit1.value then
   DBGrid1.Canvas.Brush.Color:=ColorGrid1.ForeGroundColor
 else
   DBGrid1.Canvas.Brush.Color:=ColorGrid1.BackGroundColor;
 DBGrid1.Canvas.FillRect(Rect);
 DBGrid1.Canvas.TextOut(Rect.left2,Rect.top2,Field.AsString);
end;

̵ǵSpinEdit1ʱsalaryڻSpinEdit1.ValueʱDBGrid1¼ColorGrid1ǰɫʾColorGrid1ıɫʾȻDBGridCanvasFillRectı»DBGridĻ档

3.ΪSpinEdit1OnChange¼дӦ룺

procedure TForm1.SpinEdit1Change(Sender: TObject);
begin
  DBGrid1.refresh;  //ˢǱģһҪˢŶ
end;

SpinEdit1ֵıʱˢDBGrid1

4.ΪColorGrid1OnChange¼дӦ룺

procedure TForm1.ColorGrid1Change(Sender: TObject);
begin
  DBGrid1.refresh;    //ˢǱģһҪˢŶ
  end;

ColorGrid1ֵıʱҼColorGrid1ˢDBGrid1

5.ΪForm1壨壩OnCreate¼дӦ룺

procedure TForm1.FormCreate(Sender: TObject);
begin
  ColorGrid1.ForeGroundIndex:=9;
  ColorGrid1.BackGroundIndex:=15;
  end;

ʱColorGrid1ĳֵ趨ǰΪɫΪɫҲDBGridɫΪɫɫΪɫ

6.ڣԶColorDBGridбˡҼColorGrid1ʱDBGridͱɫ֮仯

ڱУֻǼչʾԲɫʽʾDBGridԭȻӳĸԣʹʵûͬҲԽչӵCanvasԵĹУӦóûѺá
 
    

 
 2003-11-17 14:58:08    жGridǷй 
һСɣΪ˷ͳһĻǲҪˡ



  if (GetWindowlong(Stringgrid1.Handle, GWL_STYLE) and WS_VSCROLL) <> 0 then
    ShowMessage('Vertical scrollbar is visible!');
  if (GetWindowlong(Stringgrid1.Handle, GWL_STYLE) and WS_HSCROLL) <> 0 then
    ShowMessage('Horizontal scrollbar is visible!');

 

 
 2003-11-17 15:04:27    Gridͬ 
   ʵһĿУʱҪgridһͬԼûĲϣǶδһĲοֵ

{1.}

unit SyncStringGrid;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,Dialogs, Grids;

type
  TSyncKind = (skBoth, skVScroll, skHScroll);
  TSyncStringGrid = class(TStringGrid)

private
  FInSync: Boolean;
  FsyncGrid: TSyncStringGrid;
  FSyncKind: TSyncKind;
{ Private declarations }
  procedure WMVScroll(var Msg: TMessage); message WM_VSCROLL;
  procedure WMHScroll(var Msg: TMessage); message WM_HSCROLL;

protected
{ Protected declarations }

public
{ Public declarations }
  procedure DoSync(Msg, wParam: Integer; lParam: Longint); virtual;

published
{ Published declarations }
  property SyncGrid: TSyncStringGrid read FSyncGrid write FSyncGrid;
  property SyncKind: TSyncKind read FSyncKind write FSyncKind default skBoth;
end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', [TSyncStringGrid]);
end;

procedure TSyncStringGrid.WMVScroll(var Msg: TMessage);
begin
  if not FInSync and Assigned(FSyncGrid) and (FSyncKind in [skBoth, skVScroll]) then
    FSyncGrid.DoSync(WM_VSCROLL, Msg.wParam, Msg.lParam);
  inherited;
end;

procedure TSyncStringGrid.WMHScroll(var Msg: TMessage);
begin
  if not FInSync and Assigned(FSyncGrid) and (FSyncKind in [skBoth, skHScroll]) then
    FSyncGrid.DoSync(WM_HSCROLL, Msg.wParam, Msg.lParam);
  inherited;
end;

procedure TSyncStringGrid.DoSync(Msg, wParam: Integer; lParam: Longint);
begin
  FInSync := True;
  Perform(Msg, wParam, lParam);
  FinSync := False;
end;

end.

{****************************************}

{2.}
private
  OldGridProc1, OldGridProc2: TWndMethod;
  procedure Grid1WindowProc(var Message: TMessage);
  procedure Grid2WindowProc(var Message: TMessage);

public
{...}

procedure TForm1.Grid1WindowProc(var Message: TMessage);

begin
  OldGridProc1(Message);
  if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL) or Message.msg = WM_Mousewheel)) then
  begin
    OldGridProc2(Message);
  end;
end;

procedure TForm1.Grid2WindowProc(var Message: TMessage);
begin
  OldGridProc2(Message);
  if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL) or (Message.msg = WM_Mousewheel)) then
  begin
    OldGridProc1(Message);
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  OldGridProc1 := StringGrid1.WindowProc;
  OldGridProc2 := StringGrid2.WindowProc;
  StringGrid1.WindowProc := Grid1WindowProc;
  StringGrid2.WindowProc := Grid2WindowProc;
end;
     

 
 2003-11-19 9:35:04    DelphiDBGrid ÿһеɫ׷ 
   Delphiʹ DBGrid ؼʱÿһжܰҪظıɫҪıÿһеɫȴѣôڲ¿Ƽ£ûкõİ취DBGridûԼҪıÿһɫģУһּ򵥵ķ 

    ҪıDBGridÿһеɫֻҪONDrawColumnCell¼趨Ҫıɫе
ָDBGridCanvas.Brush.colorԲҰCanvas.pen.modepmmaskٵDBGrid DefaultDrawColumnCellɡעڸıǰҪȱԭ 
Canvas.Brush.color Եֵ DefaultDrawColumnCell Ҫԭֵ
أ Delphi\demos\db\clientmd Ŀ¼µʾ clintproj.dpr Ϊ,˵ǶԳеդ MemberGrid ĺнбɫɺ屳ɫģеɫΪ壬ɫֻ DrawColumnCelL ¼Ĳ䣬£ 

procedure TClientForm.MemberGridDrawColumnCell(Sender: TObject; const Rect: TRect; 
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var 
  oldcolor:tcolor;
  oldpm:tpenmode;
begin
  if DM.ProjectTEAM_LEADER.Value = DM.Emp_ProjEMP_NO.Value then  {趨ɫе}
     MemberGrid.Canvas.Font.Style := [fsBold];
     MemberGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
     {ʾԭݣӲ}
  if DM.ProjectTEAM_LEADER.Value =DM.Emp_ProjEMP_NO.Value then {趨ɫе}
  begin
     oldpm:= MemberGrid.Canvas.pen.mode;
     oldcolor:= MemberGrid.Canvas.Brush.color;
     MemberGrid.Canvas.Brush.color:=clyellow;
     MemberGrid.Canvas.pen.mode:=pmmask;
     MemberGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
     MemberGrid.Canvas.Brush.color:=oldcolor;
     MemberGrid.Canvas.pen.mode:=oldpm;
  end;
 
end;
 
    оǰļɫƷԭһģͨONDrawColumnCell¼ʵֱɫĿĹܡ 

 
 2003-11-19 9:43:56    DBGridֶ֧¼ѡ 
   ĵԹ⣬Կһ£ãƼѧϰʹá
Question How to do multi-selecting records in TDBGrid?
    When you add [dgMultiSelect] to the Options property of a DBGrid, you give yourself the ability to select multiple records within the grid.
    The records you select are represented as bookmarks and are stored in the SelectedRows property.
    The SelectedRows property is an object of type TBookmarkList.  The properties and methods are described below.

// property SelectedRows: TBookmarkList read FBookmarks;

//   TBookmarkList = class
//   public
     {* The Clear method will free all the selected records within the DBGrid *}
     // procedure Clear;
     {* The Delete method will delete all the selected rows from the dataset *}
     // procedure Delete;
     {* The Find method determines whether a bookmark is in the selected list. *}
     // function  Find(const Item: TBookmarkStr;
     //      var Index: Integer): Boolean;
     {* The IndexOf method returns the index of the bookmark within the Items property. *}
     // function IndexOf(const Item: TBookmarkStr): Integer;
     {* The Refresh method returns a boolean value to notify whether any orphans were dropped (deleted) during the time the record has been selected in the grid.  The refresh method can be used to update the selected list to minimize the possibility of accessing a deleted record. *}
     // function  Refresh: Boolean;  True = orphans found
     {* The Count property returns the number of currently selected items in the DBGrid *}
     // property Count: Integer read GetCount;
     {* The CurrentRowSelected property returns a boolean value and determines whether the current row is selected or not. *}
     // property CurrentRowSelected: Boolean
     //      read GetCurrentRowSelected
     //      write SetCurrentRowSelected;
     {* The Items property is a TStringList of TBookmarkStr *}
     // property Items[Index: Integer]: TBookmarkStr
     //      read GetItem; default;
//  end;

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, DBGrids, DB, DBTables;

type
  TForm1 = class(TForm)
    Table1: TTable;
    DBGrid1: TDBGrid;
    Count: TButton;
    Selected: TButton;
    Clear: TButton;
    Delete: TButton;
    Select: TButton;
    GetBookMark: TButton;
    Find: TButton;
    FreeBookmark: TButton;
    DataSource1: TDataSource;
    procedure CountClick(Sender: TObject);
    procedure SelectedClick(Sender: TObject);
    procedure ClearClick(Sender: TObject);
    procedure DeleteClick(Sender: TObject);
    procedure SelectClick(Sender: TObject);
    procedure GetBookMarkClick(Sender: TObject);
    procedure FindClick(Sender: TObject);
    procedure FreeBookmarkClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  Bookmark1: TBookmark;
  z: Integer;

implementation

{$R *.DFM}

//Example of the Count property
procedure TForm1.CountClick(Sender: TObject);
begin
  if DBgrid1.SelectedRows.Count > 0 then
  begin
    showmessage(inttostr(DBgrid1.SelectedRows.Count));
  end;
end;

//Example of the CurrentRowSelected property
procedure TForm1.SelectedClick(Sender: TObject);
begin
  if DBgrid1.SelectedRows.CurrentRowSelected then
    showmessage('Selected');
end;

//Example of the Clear Method
procedure TForm1.ClearClick(Sender: TObject);
begin
  dbgrid1.SelectedRows.Clear;
end;

//Example of the Delete Method
procedure TForm1.DeleteClick(Sender: TObject);
begin
  DBgrid1.SelectedRows.Delete;
end;

{*
   This example iterates through the selected rows of the grid and displays the second field of the dataset.
   The Method DisableControls is used so that the DBGrid will not update when the dataset is changed. The last position of the dataset is saved as a TBookmark.
   The IndexOf method is called to check whether or not the bookmark is still existent.
   The decision of using the IndexOf method rather than the Refresh method should be determined by the specific application.
*}

procedure TForm1.SelectClick(Sender: TObject);
var
  x: word;
  TempBookmark: TBookMark;
begin
  DBGrid1.Datasource.Dataset.DisableControls;
  with DBgrid1.SelectedRows do
  if Count > 0 then
  begin
    TempBookmark:= DBGrid1.Datasource.Dataset.GetBookmark;
    for x:= 0 to Count - 1 do
    begin
      if IndexOf(Items[x]) > -1 then
      begin
        DBGrid1.Datasource.Dataset.Bookmark:= Items[x];
        showmessage(DBGrid1.Datasource.Dataset.Fields[1].AsString);
      end;
    end;
  end;
  DBGrid1.Datasource.Dataset.GotoBookmark(TempBookmark);
  DBGrid1.Datasource.Dataset.FreeBookmark(TempBookmark);
  DBGrid1.Datasource.Dataset.EnableControls;
end;

{*
This example allows you to set a bookmark and  and then search for the bookmarked record within selected a record(s) within the DBGrid.
*}

//Sets a bookmark
procedure TForm1.GetBookMarkClick(Sender: TObject);
begin
  Bookmark1:= DBGrid1.Datasource.Dataset.GetBookmark;
end;

//Frees the bookmark
procedure TForm1.FreeBookmarkClick(Sender: TObject);
begin
  if assigned(Bookmark1) then
  begin
    DBGrid1.Datasource.Dataset.FreeBookmark(Bookmark1);
    Bookmark1:= nil;
  end;
end;

//Uses the Find method to locate the position of the bookmarked record within the selected list in the DBGrid
procedure TForm1.FindClick(Sender: TObject);
begin
  if assigned(Bookmark1) then
  begin
    if DBGrid1.SelectedRows.Find(TBookMarkStr(Bookmark1),z) then
      showmessage(inttostr(z));
  end;
end;

end. 

 
 2003-11-19 10:11:21    һֿDelphiDBGrid ÿһɫķ 
   иDelphiʹDBGridʱDBGridÿһɫûԼԸ
ơʱΪǳǳ򵥣϶׼ȴֲ
ô£ͳܷáڵǰһֱ賿4㣬ϵصԣ˵ƾƽʱ۵һ̾飬ҵ˿ŵĳԿֽ乫á 

   1 ݱĽ 
   DelphiĹ߲˵ѡDatabase desktopݿDBDemos½һΪ
example.dbݱݱֶκ£ 
              
Name  Age  Wage
ɽ  25  500
  57  1060
  30  520
ţ  28  390

    2TDBGridTColoredDBGrid 
    Delphi˵УѡNew Component,ڵԻã 

Ancestor Type  =   TDBGrid
Class  Name   =   TColoredDBGrid

    Ȼ󵥻OKťDelphiԶܵĶ塣OnDRawColoredDBGrid¼
ʹObject InspectorEventsԱӦó趨ıɫ
DrawCellֻԼƵԪ񡣲ͨOnDrawColumnCellɫΪ
OnDrawColumnCellı䵥ԪɫٴδOnDrawColumnCell 
    Դ  

    3Ӧó֤ 
    Delphiļ˵ѡNewµӦó򹤳Project1Form1Form1
CaptionΪDBGridɫʾData SourceTableButton
ColoredDBGridø£ 

Table1.Database=DBDemos
Table1.Tablename=example.db
Datasource1.Dataset=Table1
ColoredDBGrid1.Datasource=DataSource1
Button1.Caption=˳

    ColoredDBGrid1onDRawColoredDBGrid¼д룬趨Wageʣ
ColoredDBGrid1еɫ 

procedure TForm1.ColoredDBGrid1 DRawColoredDBGrid (Sender: TObject;  Field: TField; var Color: TColor; var Font: TFont);
Var
    p : Integer;
begin
    p := Table1.FindField('wage').AsInteger;
  //ȡõǰ¼Wageֶεֵ
    if (p < 500) then begin                 
//򽫸wageֵøеɫ
      Color := clGreen;
      Font.Style := [fsItalic];      
//Ըıɫ,Ըı
    end;
    if(p >= 500) And (p < 800) then
      Color := clRed;
    if(p >=800) then begin
      Color := clMaroon;
      Font.Style := [fsBold];
    end;
end;
//á˳ťС
procedure TForm1.Button1Click(Sender: TObject);
begin
    Close;
end; 

 
 2003-11-19 10:16:11    һDbgridʾݿ 
   ݿУҪҲܽӦóݿֶηһݿļСȷݿṹӦǣݿֶηݿļصݿⶼһΨһ
ĹؼֶΣڶݿṹԽϵ 
    磺Ҫһ¹Ϊʾֻݿ⣬ÿݿⶼֻ
ֶΡ 
    ˼ jianjie.dbf´ά gongzi.dbfɲά 
    1.ݿĽ 
    DataBase Desktopݿṹ£
    
    jianjie.dbf
     ֶ:bianhao size:4 type:number
     ֶ:xingming size:10 type:character

    gongzi.dbf
     ֶ:bianhao size:4 type:number
     ֶ:gongzi size:4 Dec 2 type:number

    ע⣺ ݿbianhaoֶεsizetypeһ¡ʵϣݿļԷֲ
ĲͬϣΪʾֱΪc: \test\jianjie.dbf c:\test
\gongzi.dbf塣 

    2.Ӧóı 
    Delphi ½һ̣ڴмQueryؼQuery1databasenameΪc:
\test 

    DataSourceؼdatasource1 DataSetΪQuery1 DbGridؼ dbgrid1
DataSourceΪDataSource1Query1.sqlΪ 

    SELECT DISTINCT A.bianhao,a.xingming, b.gongzi
    FROM jianjie.dbf A, gongzi.DBF b
    WHERE A.bianhao=b.bianhao

    ٽQuery1.enabledΪTrue ñ룬 DbGrid1ͻʾ: bianhao 
xingming gongziֶΡjianjie.dbfgongzi.dbfм¼¼ʾ
ƪޣֻDbgridʾݿݵһ㷽߿ڴ˻Ͻ
ƣʹ÷õӦҪ 
  

 
 2003-11-19 10:19:40     DBGrid ûسΪƶ 

Form.OnKeyPress¼д´룺

  if Key = #13 then 
  if ActiveControl = DBGrid1 then begin 
    TDBGrid(ActiveControl).SelectedIndex := TDBGrid(ActiveControl).SelectedIndex + 1; 
    Key := #0; 
end; 

2Ҫע⣺
  1.ﵽDBGirdеʱٰس껹ͣԭء
  2.Key := #0 

 
 2003-11-19 10:25:07     DBGrid иƼ¼ 
procedure TForm1.DBGrid1DblClick(Sender: TObject);
var
   x : integer ;
   HadToOpen : boolean ;
begin
   with Sender as TDBGrid do begin
      HadToOpen := not tTarget.Active ;
      if HadToOpen then
         tTarget.Active := True ;
      tTarget.Append ;
      for x := 0 to FieldCount - 1 do
         case Fields[x].DataType of
            ftBoolean : tTarget.FieldByName(Fields[x].FieldName).AsBoolean := Fields[x].AsBoolean
            ftString : tTarget.FieldByName(Fields[x].FieldName).AsString := Fields[x].AsString
            ftFloat : tTarget.FieldByName(Fields[x].FieldName).AsFloat := Fields[x].AsFloat
            ftInteger : tTarget.FieldByName(Fields[x].FieldName).AsInteger := Fields[x].AsInteger
            ftDate : tTarget.FieldByName(Fields[x].FieldName).AsDateTime := Fields[x].AsDateTime ;
         end ;
      tTarget.Post ;
      if HadToOpen then
         tTarget.Active := False ;
   end ;
end; 

 
 2003-11-19 10:27:58    ʹ DBGrid ĸѡοDBGridֶ֧¼ѡ 
procedure TForm1.SelectClick(Sender: TObject);
var
  x: word;
  TempBookmark: TBookMark;
begin
  DBGrid1.Datasource.Dataset.DisableControls;
  with DBgrid1.SelectedRows do
    if Count <> 0 then
    begin
      TempBookmark:= DBGrid1.Datasource.Dataset.GetBookmark;
      for x:= 0 to Count - 1 do
      begin
        if IndexOf(Items[x]) > -1 then
        begin
          DBGrid1.Datasource.Dataset.Bookmark:= Items[x];
          showmessage(DBGrid1.Datasource.Dataset.Fields[1].AsString);
        end;
      end;
    end;
  DBGrid1.Datasource.Dataset.GotoBookmark(TempBookmark);
  DBGrid1.Datasource.Dataset.FreeBookmark(TempBookmark);
  DBGrid1.Datasource.Dataset.EnableControls;
end;

  

 
 2003-11-19 10:32:27    DBGridDrag & DropϷţ 
з֣ܹûһEditֱϷŵһDBGridԵúܷ㣬ڳƹз֣ƺϷֻϷŵǰļ¼ϣǼҪϷŵ¼ôأܲûѡ¼ȻϷŰɡ
    ͨо֣DBGridʱDBGridԶ¼ָƶļ¼ϣ͸һ˼·óģDBGridϵһεùƶ¼ϣȻͿԽϷŵдDBgridˡ
    ͨʵ֤˼·ǿеġ棬Ҿ͸ߴҵ
    1) FormϷһDBGridܹʾ¼(Ƚϼ򵥣Ͳö˵)
    2) FormϷһEdit
    3) ޸EditԣDragModeΪdmAutoMatic, ûܹϷ
    4) DbgridDragOver¼´룺 ܹ Drag & drop

procedure TForm1.DBGrid1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
  accept:=true;
end;

    5) DbgridDragDrop¼´룺 ܹԶָļ¼

procedure TForm1.DBGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
begin
  if Source<>Edit1 then exit;
  with Sender as TDbGrid do begin
    Perform(wm_LButtonDown,0,MakeLong(x,y));
    PerForm(WM_LButtonUp,  0,MakeLong(x,y));
    SelectedField.Dataset.edit;
    SelectedField.AsString:=Edit1.text;
  end;
end;

    ˣǾʵҪĹܣPerFormTControlһͨ÷ĿƹWindowsϢѭϢֱӷҪControlʹ÷οDelphiİ 

 
 2003-11-19 10:39:19    ʹDBGridָ벻ƶ 

⡿DBGRIDʾTABLEе,ҪͷβһTABLE,
Table1.First,NextʹDBGRIDָҲ,ôʹʱDBGRIDָ벻
?

𰸡ʹ´뼴ɣ

with DataSet do
try
  DisableControls;
  Do_something;
finally
  EnableControls;
end; 

 
 2003-11-19 10:42:14    ζ̬DBGridɫͬʱοʹDBGRIDɫ˸еֵı仯仯 
   DBGridؼһûӿڵʾݿĿؼµĳθʾݸıʾɫ磬һе˿ڴ200ǾʾΪɫʹõĿؼ¼ΪDBGrid.OnDrawColumeCell.

  procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect:TRect;DataCol: 
Integer; Column: TColumn; State: TGridDrawState);
  begin
    if Table1.FieldByName('Population').AsInteger > 20000000 then
      DBGrid1.Canvas.Font.Color := clBlue;
    DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
  end;

    Ǽ򵥵ģԸԼҪ䣬Ҳ仯ȣԵûԲĺϻһɫԲȦ 

 
 2003-11-19 10:45:14    ʹDBGridʾ 
   ʹ DBGRID ؼʱʾ DATATIME ʱΪ2λģڲ2000Ҫʾ4λ磺19982001ݿиֶֻ2000Żʾ4λôأ ǾøֶDBGRIDؼҲʾ4λڸʽ ˫ Table1 ؼͻ form1.table 壬Ҽѡ Add Fields...ѡֶκokоͳݿֶڵǸֶԿͳ˸ֶεϢһ DispalyFormatڸʾʽ yyyy.mm.dd ôDBGRIDؼͳˡ 

 
 2003-11-19 10:48:37    TDBGridؼʵϷŵһ˼·ͬʱοDBGridDrag & DropϷţ 
   ڱunitУԶTMyCustomDBGrid=class(TCustomDBGrid),:

    TMyCustomDBGrid(DBGrid1).MouseDown(...)
  
    DBGrid1 as TMyCustomDBGrid).MouseDown(...)ɡ 

 
 2003-11-19 10:56:11    dbgridðس൱ڵclick 
̡
    ڴform1зtable1,datasource1,dbgrid1,ϵʹ dbgrid1 ȷʾtable1ݡȻ
procedure TForm1.DBGrid1KeyPress(Sender: TObject;
var Key: Char);
begin
  with DBGrid1 do
    if Key=#13 then
      DBGrid1CellClick(Columns[SelectedIndex]);
end;

procedure TForm1.DBGrid1CellClick(Column: TColumn);
begin
  with DBGrid1 do
    showmessage(format('row=%d',[SelectedIndex]));
end; 

 
 2003-11-19 11:07:55    Delphi  DBGrid ебͲֶα̷ 
   ǷǳеʾʽϤExcelVFP еĹǿBROWS ȣΪԱڲá Delphi ݿӦϵͳʱDBGrid ʱЩֶֻĳ̶ַ񵵰ıޣֻСáڡ͡ڡ֣ɷһбнѡ񣬴ӶͱأһЩֶΣְϢеĵλţĵλбŵλϸϢʾְʱܷ񲻶ԵλŽв֮ڸֱ۵ĵλеĵλأǿ϶ģDelphi ؼ DBGrid֧бͲֶεı̣ң̵Ĺ̶ǿӻģҪдһ䡣 

һDBGrid еб
     DBGrid ʵбú DBGrid иֶε PickList ַбʼֵ DropDownRows ɡְϢеļֶΣַͣΪƲ£ 
  1ڴϷTable1DataSource1DBGrid1DBNavigator1 ȿؼ󣬰±ø: 

---------------------------------------
                趨ֵ
---------------------------------------
Table1       DataBase     sy1
             Table        zgk.dbf   //ְϢ
DataSource1  DataSet      Table1
DbGrid1      DataSource   DataSource1
DBNavigator1 DataSource   Datasource1
-------------------------------------------
  2˫Table1, ڵForm1.Table1 УҼݲ˵Add Fields ˵ѡеֶκ󣬰OK ť 

  3޸ĵ2 ֶε DisplayLabel ԡ Table1ZGBH ֶΪ Object Inspector ѡ Table1ZGBH, ޸ DisplayLabel= ְţֶơ 

  4˫ DBGrid1, ڵ Editing DBGrid1.Columns У Add all Fields ťTable1 ֶΡ 

  5 Editing DBGrid1.Columns ڣѡ jg һУл Object Inspector ڣ޸ PickList.Strings Ϊ֦УУУУƽɽУУ㽭С 

  6 Form1.Oncreate ¼д䣺 

   Table1.Open; 

  7F9 Уĳ¼ļֶΣұ߼һťťɳһб5 ַѡ񡣵ȻҲһбеַ 

DBGrid еĲֶ
    νֶ (LookUp Field) DBGrid еĳؼֶεֵԴһݿӦֶΡòֶμЧı󣬶 DBGrid ʾʽΪԲʾؼֶΣʾԴݿӦһֶεݡ 
---- 磬 DBGrid ʾͱ༭ְϢְšְᡢڵλţλԴһݿ񡪡λ⣬ơλšΪؼֶΡֱʾͱ༭λŵĻ123 ȷǳֱ۵֣༭ʱ׳ʾͱ༭ǵλжӦĵλƻǳֱۡDBGrid ֵ֧Ĳֶδĺô 

    ʵDBGrid ĲֶͬҪκ䣬Ʋ£ 
  1ڴϷ Table1Table2DataSource1DBGrid1DBNavigator1 ȿؼ󣬰±ø: 

---------------------------------------
                趨ֵ
---------------------------------------
Table1       DataBase     sy1
             Table        zgk.dbf   //ְϢ
Table2       DataBase     sy1
             Table        dwk.dbf   //λϢ
DataSource1  DataSet      Table1
DbGrid1      DataSource   DataSource1
DBNavigator1 DataSource   Datasource1
------------------------------------------
  2˫ Table1, ڵ Form1.Table1 УҼݲ˵ Add Fields ˵ѡеֶκ󣬰OK ť 

  3޸ĵ2 ֶε DisplayLabel ԡ Table1ZGBH ֶΪ Object Inspector ѡ Table1ZGBH, ޸ DisplayLabel= ְţֶơ 

  4 Table1DWBH.Visible=False 

  5 Form1.Table1 ڣҼݲ˵ New Field ˵һֶDWMCڵĴӦ,  OK ťȷϣ Object Inspector ڣ Table1DWMC.DisplayLabel= λơ 

  6 Form1.Oncreate ¼д䣺 

    Table1.Open; 

  7 F9 Уĳ¼ĵλֶʱֶΣһбұߵ¼ͷбнѡԿбڵλϢ⣬Ҳݡ 

DBGrid ебͲֶε
    Ȼ DBGrid ебͲֶΣбʽֵģкܴĲ 
  1 PickList õбֹģȻҲڳ޸ģ̬ȻֱݿȡݵĲֶΡ 

  2 PickList õб벻беݣֶֻԴݿйؼֶеݣܱ֤ݵԡ 

  3 PickList õбƽΪ򵥡  

 
 2003-11-19 11:23:29    DelphiжDBGridؼ 
Delphi,DBGridؼһݿܲʹõĿؼ,书ܷǳǿ,SQLʵּݱʾ,Ҳǳ,ԡ̡¼ȶǳֱ,ʹ,ʱҪһЩ,ӡʾDBGridеת浽Excel97еȵȡҪǶDBGrid,ԸõӦǵʵҪDBGrid,ʵоٵĹ,ڴӡDBGridĻQuickReportĹ,ֱӽDBGridĴӡԤ,ûоQuickReportĴ,ֻ÷WpaperPreview;תݵExcelҲһ,ʹõԶExcelѡڳ̫,ϸо,һʵְʾDBGrid,NewDBGridС,߿áࡢʵõĹܡ 
NewDBGridʵԭǼ̳DBGridй,ͬʱµԣ
       Wzebra,WfirstColor ,WsecondColor
    WzebraֵΪTrueʱ,ʾЧ,ʾЧǵɫΪWfirstColor,˫ɫΪWsecondColorļ嵥: 

unit NewDBGrid;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB, Grids, DBGrids, Excel97;
type
  TDrawFieldCellEvent = procedure(Sender: TObject; Field: TField;
    var Color: TCOlor; var Font: TFont; Row: Longint) of object;
//µݿؼ TDBGrid ̳ж
  TNewDBGrid = class(TDBGrid)

  private
//˽б
    FWZebra: Boolean; //Ƿʾɫ
    FWFirstColor: TColor; //ɫ
    FWSecondColor: TCOlor; //˫ɫ
    FDrawFieldCellEvent: TDrawFieldCellEvent;
    procedure AutoInitialize; //Զʹ
    procedure AutoDestroy;
    function GetWFirstColor: TColor;
//FirstColor Ķд
    procedure SetWFirstColor(Value: TColor);
    function GetWSecondColor: TCOlor;
    procedure SetWSecondColor(Value: TColor);
    function GetWZebra: Boolean;
    procedure SetWZebra(Value: Boolean);

  protected
    procedure Scroll(Distance: Integer); override;
//ؼص
    procedure DrawCell(Acol, ARow: Longint; ARect:
      TRect; AState: TGridDrawState); override;

  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

  published
    property WZebra: Boolean read GetWZebra write SetWZebra;
    property OnDblClick;
    property OnDragDrop;
    property OnKeyUp;
    property OnKeyDown;
    property OnKeyPress;
    property OnEnter;
    property OnExit;
    property OnDrawDataCell;
    property WFirstColor: TColor
      read GetWFirstColor write SetWFirstColor;
    property WSecondColor: TColor
      read GetWSecondColor write SetWSecondColor;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Data Controls', [TNewDBGrid]);
end;

procedure TNewDBGrid.AutoInitialize;
begin
  FWFirstColor := RGB(239, 254, 247);
  FWSecondColor := RGB(249, 244, 245);
{ڴҪؼʹ}
end;

procedure TNewDBGrid.AutoDestroy;
begin
{ͷԼӲռõϵͳԴ}
end;

procedure TNewDBGrid.SetWZebra(Value: Boolean);
begin
  FWZebra := Value;
  Refresh;
end;

function TNewDBGrid.GetWZebra: Boolean;
begin
  Result := FWZebra;
end;

function TNewDBGrid.GetWFirstColor: TColor;
begin
  Result := FWFirstColor;
end;

procedure TNewDBGrid.SetWFirstColor(Value: TColor);
begin
  FWFirstColor := Value;
  Refresh;
end;

function TNewDBGrid.GetWSecondColor: TColor;
begin
  Result := FWSecondColor;
end;

procedure TNewDBGrid.SetWSecondColor(Value: TColor);
begin
  FWSecondColor := Value;
  Refresh;
end;

constructor TNewDBGrid.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  AutoInitialize;
end;

destructor TNewDBGrid.Destroy;
begin
  AutoDestroy;
  inherited Destroy;
end;
//ʵְЧ

procedure TNewDBGrid.DrawCell(ACol, ARow:
  Longint; ARect: TRect; AState: TGridDrawState);
var
  OldActive: Integer;
  Highlight: Boolean;
  Value: string;
  DrawColumn: Tcolumn;
  cl: TColor;
  fn: TFont;
begin
{ڿؼװ״̬,ֱɫ˳}
  if csLoading in ComponentState then
  begin
    Canvas.Brush.Color := Color;
    Canvas.FillRect(ARect);
    Exit;
  end;
  if (gdFixed in AState) and (ACol - IndicatorOffset < 0) then
  begin
    inherited DrawCell(ACol, ARow, ARect, AState);
    Exit;
  end;
{б,κ}
  if (dgTitles in Options) and (ARow = 0) then
  begin
    inherited DrawCell(ACol, ARow, ARect, AState);
    Exit;
  end;
  if (dgTitles in Options) then Dec(ARow);
  Dec(ACol, IndicatorOffset);
  if (gdFixed in AState) and ([dgRowLines, dgColLines] * Options =
    [dgRowLines, dgColLines]) then
  begin
{ARect,Աд}
    InflateRect(ARect, -1, -1);
  end
  else
    with Canvas do
    begin
      DrawColumn := Columns[ACol];
      Font := DrawColumn.Font;
      Brush.Color := DrawColumn.Color;
      Font.Color := DrawColumn.Font.Color;
      if FWZebra then //WZebraΪTrueʾ
        if Odd(ARow) then
          Brush.Color := FWSecondColor
        else
          Brush.Color := FWFirstColor;
      if (DataLink = nil) or not DataLink.Active then
        FillRect(ARect)
      else
      begin
        Value := '';
        OldActive := DataLink.ActiveRecord;
        try
          DataLink.ActiveRecord := ARow;
          if Assigned(DrawColumn.Field) then
          begin
            Value := DrawColumn.Field.DisplayText;
            if Assigned(FDrawFieldCellEvent) then
            begin
              cl := Brush.Color;
              fn := Font;
              FDrawFieldCellEvent(self, DrawColumn.Field, cl, fn, ARow);
              Brush.Color := cl;
              Font := fn;
            end;
          end;
          Highlight := HighlightCell(ACol, ARow, Value, AState);
          if Highlight and (not FWZebra) then
          begin
            Brush.Color := clHighlight;
            Font.Color := clHighlightText;
          end;
          if DefaultDrawing then
            DefaultDrawColumnCell(ARect, ACol, DrawColumn, AState);
          if Columns.State = csDefault then
            DrawDataCell(ARect, DrawColumn.Field, AState);
          DrawColumnCell(ARect, ACol, DrawColumn, AState);
        finally
          DataLink.Activerecord := OldActive;
        end;
        if DefaultDrawing and (gdSelected in AState) and
          ((dgAlwaysShowSelection in Options) or Focused)
          and not (csDesigning in Componentstate)
          and not (dgRowSelect in Options)
          and (ValidParentForm(self).ActiveControl = self) then
        begin
//ʾǰ괦Ϊ׻,ͬʱӴʾ
          Windows.DrawFocusRect(Handle, ARect);
          Canvas.Brush.COlor := clBlue;
          Canvas.FillRect(ARect);
          Canvas.Font.Color := clYellow;
          Canvas.Font.Style := [fsBold];
          DefaultDrawColumnCell(ARect, ACol, DrawColumn, AState);
        end;
      end;
    end;
  if (gdFixed in AState) and ([dgRowLines, dgColLines] * Options =
    [dgRowLines, dgColLines]) then
  begin
    InflateRect(ARect, -2, -2);
    DrawEdge(Canvas.Handle, ARect, BDR_RAISEDINNER, BF_BOTTOMRIGHT);
    DrawEdge(Canvas.Handle, ARect, BDR_SUNKENINNER, BF_TOPLEFT);
  end;
end;
//ƶ,ҪˢʾDBGrid

procedure TNewDBGrid.Scroll(Distance: Integer);
begin
  inherited Scroll(Distance);
  refresh;
end;

end.

ϳWin98 + Delphi 5µͨ 

 
 2003-11-19 11:27:19    DBGridؼʾͼ 
ݿһΪBLOB͵ֶڱͼ,ʹDBGridؼʾʱ,ڱʾBLOB,޷ʾͼ,Ȼ,һЩؼʾͼ,Ҫȥҵؼһ׵,ЩõĶҪѡܲDBGridʾͼأǿ϶ġ
DBGridOnDrawCell¼м´뼴DBGridؼʾͼΡ
var
  Bmp: TBitmap;
begin
  if (Column.Field.DataTyp = ftBLOB) or (Column.Field.DataTyp = ftGraphic) then
  begin
    Bmp:=TBitmap.Create;
    try
      Bmp.Assign(Column.Field);
      DBGrid1.Canvas.StretchDraw(Rect,Bmp);
      Bmp.Free;
    Except
      Bmp.Free;
    end;
  end;
end;
Ƶķ,ͿDBGridʾMemo͵ֶݡ
,ݿбͼʱ,ʹEMFͼԪļ,ݿļĴСʮ־,Թ,ͬһ400*300ͼ,λͼ,100ʱ,ݿļСﵽ20MB,ʹEMFʸͼα,800ʱ260KB,EMFʸͼεķ뱣λͼǲ,DBGridʾҲ,ֻBLOBֶݲֱAssignEMFļ,ҪMemoryStreamת
  

 
 2003-11-19 11:31:15    DBGridĿǰļ¼λѶ 
   ʲ᷽ʽץαĿǰDBGridRecord? ҵ˼,α֮recordʾedit 

    ǶӦһ Edit ԪĻ,  TDBEdit  TDBLabel, ԲٷĹܼ¼λ;
    ֻһ EditBox, ҪһֱӦ DBGrid Ŀǰ¼Ŀǰλ, ǿͬʱ DataSource  OnDataChange  DbGrid  OnColEnter ¼дEditBoxݵĳʽ.
     DBGrid  OnColEnter ¼:

procedure TForm1.DBGrid1ColEnter(Sender: TObject);
begin
  if DBGrid1.SelectedField <> nil then
    Edit1.Text := DBGrid1.SelectedField.AsString;
end;

    ֻ OnColEnter ǲ, Ϊ, ͬһ Column(ͬһλ)ƶ׷ʱ, OnColEnter ǲᱻ, , ٴ OnDataChange¼,  State Ϊ dsBrowse ʱ DataChange, ͬ¼λõĸı,µĳʽǺ DBGrid  OnColEnter ¼:

procedure TForm1.DataSource1DataChange(Sender: TObject; Field: TField);
begin
  if DataSource1.State = dsBrowse then
    DBGrid1ColEnter(Sender);
end; 

 
 2003-11-19 11:39:38    DbGridedit¼ʱʾ 
DelphiṰ˲ķ,ɴݿѡ˹Ŀؼ:DBListBoxDBComboBoxDBLookupListBoxDBLookupComboBoxȡһ:ݿΪdm.db,ֶ: 
    :Code 
    :Name 
ҪûĴ,ȥȡôӦơ 
 
    һû֪ƵĶӦϵ,û,ѡӦ,ĿؼʹԱƵĶӦϵ,ûݴȥҵӦĸ¼,Ѳ 
 
    ,ұ,DBGridΪEditб,DBGridֱ۵ʾƵĶӦϵ,ܹû¼ı仯,ʱDBGridеļ¼ָ,ʹûֱ۷صȡҪ,DBGridûEditʱ,EditʧַΪû¼ṩ˷,ֲӰ,ЧְѸóṩ,ǿɸԼҪ,Գмӹ,Ӧڳ򿪷,ϣשá 
 
⡿һС:û,Ȼʾڴϡ 
 
1ǿԽһForm,ڴFormӿؼ: 
 
Table : Table1,ԶӦdm.db,ActiveΪTrue 
DataSource : DataSource1, DataSetΪTable1 
Edit : CodeEdit,NameEditֱӦʾ 
DBGrid : DBGrid1, DataSourceΪDataSource1 
CodeEditTextֵÿ,NameEditTextֵÿա 
 
2,޸CodeEditOnEnterOnExitOnKeyDownOnKeyUp¼: 
 
  CodeEditOnEnter¼: 
  procedure TForm1.CodeEditEnter(Sender: TObject); 
  begin 
    if CodeEdit.text<>'' then 
    begin 
      CodeEdit.SelStart:=length(CodeEdit.text); 
      Table1.locate('code', CodeEdit.text,[lopartialkey]); 
    End; 
  end; 
 
  CodeEditOnExit¼: 
  procedure TForm1.CodeEditExit(Sender: TObject); 
  begin 
  if activecontrol<>dbgrid1 then 
  begin 
    dbgrid1.Visible:=false; 
    Table1.Locate('code',codeedit.text,[lopartialkey]); 
    if Table1.Eof then 
    begin 
      dbgrid1.Visible:=true; 
      exit; 
    end; 
    if not Table1.Eof then 
    begin 
      codeedit.Text:=Table1.fieldbyname('code').asstring; 
      NameEdit.Text := Table1.fieldbyname('name').asstring; 
    end; 
  end; 
  end; 
 
CodeEditOnKeyDown¼: 
Procedure Tform1.CodeEditKeyDown(Sender: TObject;var Key: Word;Shift: TShiftState); 
var 
  i:integer; 
begin 
  if (Table1.RecordCount>0) then 
  begin 
    case key of 48..57: 
    begin 
      dbgrid1.Visible:=true; 
      Table1.Locate('code',CodeEdit.text,[lopartialkey]); 
    end; 
    vk_next: 
    if dbgrid1.Visible then 
    begin 
      i:=0; 
      while (not Table1.Eof) and (i<11) do 
      begin 
        Table1.Next; 
        i:=i+1; 
      end; 
      CodeEdit.Text:=Table1.fieldbyname('code').asstring; 
    End; 
    vk_prior: 
    if dbgrid1.Visible then 
    begin 
      i:=0; 
      while (not Table1.Bof) and (i<11) do 
      begin 
        Table1.prior; 
        i:=i+1; 
      end; 
      CodeEdit.Text:=Table1.fieldbyname('code').asstring; 
    end; 
    vk_down: 
    if dbgrid1.Visible then 
    begin 
      if not Table1.Eof then 
      begin 
        Table1.Next; 
        CodeEdit.Text:=Table1.fieldbyname('code').asstring; 
      end; 
    end; 
    vk_up: 
    if dbgrid1.Visible then 
    begin 
      if not Table1.Bof then 
      begin 
        Table1.Prior; 
        CodeEdit.Text:=Table1.fieldbyname('code').asstring; 
      end; 
    end; 
  end; 
  end 
  else 
    dbgrid1.Visible:=false; 
  CodeEdit.SelStart:=length(CodeEdit.text); 
end; 
 
CodeEditOnKeyUp¼: 
procedure Tform1.CodeEditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); 
begin 
  if (Table1.RecordCount>0) then 
  begin 
    if ((key>=48) and (key<=57)) then 
      Table1.Locate('code',codeedit.text,[lopartialkey]); 
    if (key=VK_back) and (codeedit.text<>'') then 
      Table1.Locate('code',codeedit.text,[lopartialkey]); 
    if (key=VK_BACK) and (codeedit.text='') then 
      Table1.First; 
    if (key=vk_down) or (key=vk_up) or (key=vk_prior) or (key=vk_next) then 
      if dbgrid1.Visible then 
        codeedit.Text:=Table1.fieldbyname('code').asstring; 
  end 
  else 
    dbgrid1.Visible:=false; 
    codeedit.SelStart:=length(codeedit.text);  
end; 
 
Windows98+Delphi4.05.0¾ͨ  

 
 2003-11-19 11:49:55    DelphidbgridиݵԲͬʾͬɫ 
ͬʱοζ̬DBGridɫ/ʹDBGRIDɫ˸еֵı仯仯

    Ӧϵͳ,ûҪݰͬɫʾ,ֻҪ Dbgrid  DrawColumnCell ¼м´Ϳ:
If Query.fieldbyname('ֶ').values  then
  Begin
    Dbgrid.Canvas.Brush.Color := ɫ(:clInfoBk) ;
    Dbgrid.DefaultDrawColumnCell( Rect, DataCol, Column, [gdFixed,gdFocused,gdSelected] );
  End ; 

 
 2003-11-19 12:00:18    DBGridܣͬʱοDBGridTitleԲѯ򡱣 

    ʵݿϵͳУûԱݵĲƵĪѯˣѯṩΪĳֶνܣǳûԡؼݡ˽⡣ 

    Windowsû֪ڡҵĵԡԴдһļУԡϸϡʽ鿴ϵͳʾļµļкļϢ磺ơ С޸ʱ䣬ûֻҪеӦϵͳԶС򡱣򡰽򡱣ʾûɲ鿴Ӧļлļݡ 

    ܴܲʾݵGrid˹أǿ϶ġDelphiеʵַΪͨݣܸùܵʵ֡ 
£ 

һȽһݱ 
    ñDelphi õParadoxΪͣȡΪStudentӳְѧĻñֶζ£ 
-------------------------------------------- 
ֶ͡С 
šShort͡/ (Key*) 
ѧšAlpha͡6 
ڡDate͡ / 
Ա𡡡Alpha͡2 
񡡡Logical͡/ 
ӢNumber͡ / 
Number͡ / 
PASCALNumber͡ / 
עMemo͡ 20 
------------------------------------------- 
35¼ݡ 

עٱб뽨ؼΪֶν˴ΪšֶΣ 
    ڸñʹParadoxõļֶͣδȫ 

Ŀʵֹ 
1½һĿΪؿؼؼҪ± 

2Click¼ 

Button1(򿪱)Click¼£ 
procedure TForm1.Button1Click(Sender: TObject); 
begin 
  Table1.Open; // Table1ıStudent 
end; 

Button2(رձ)Click¼£ 
procedure TForm1.Button2Click(Sender: TObject); 
begin 
  Application.Terminate; 
end; 

DBGrid1TitleClick¼£ 
procedure TForm1.DBGrid1TitleClick(Column: TColumn); 
//ע̲ColumnϢǳ 
begin 
  MySort(DBGrid1,Column); 
end; //ֶ 
УMySort(DBGrid1,Column)ΪԶ̣ 

3ͨôģ 
    ΪʹùܾСͨԡ䶨Ϊһ̡ 
ȣԤ̼ȫ˽б 

... 
Type 
... 

procedure MySort(DBGrid0:TDBGrid; Column: TColumn);//Ԥ 

private 

  { Private declarations } 
  psIndexName:string; //¼ǰ 
  plAscend:boolean; //¼ǰƵ״̬ 

public 
  { Public declarations } 

end; 

... 

Σù£ 

procedure TForm1.MySort(DBGrid0:TDBGrid; Column: TColumn); 
var 
//ģʹõpsIndexName, plAscend϶ 
  mode:char; //¼ǡ򡱻ǡ 
  ColName:string; //¼ǰֶ 
  iCol:Integer; //¼ǰк 

begin 
  with DBGrid0.DataSource.DataSet as TTable do //Table0 
  begin 
//⵱ǰǷѴ 
    if not Active 
    then begin 
      MessageBeep(0); 
      Application.MessageBox('δ򿪣','ֹͣ',MB_OK+MB_ICONSTOP); 
      Abort 
    end; 

//⵱ǰֶǷ򡱡ֶͲ 
    case Column.Field.DataType of 
      ftBoolean, 
      ftBytes, 
      ftBlob, //Binary 
      ftMemo, 
      ftGraphic, 
      ftFmtMemo, //Formatted memo 
      ftParadoxOle: //OLE 
      begin 
        MessageBeep(0); 
        Application.MessageBox(Pchar('Ŀ"'+Column.FieldName+'"'+''),'ֹͣ',MB_OK+MB_ICONSTOP); 
        Abort 
      end; 
  end; //case 
  mode:='0'; 
  iCol:=Column.Field.FieldNo-1; 
  try 
    ColName:=Column.fieldname; 
    if psIndexName=Column.fieldname 
    then begin //ԭͬ 
      if plAscend // 
      then begin 
        mode:='2'; 
        IndexName:=ColName+'2'; //Ӧ 
      end 
      else begin 
        mode:='1'; 
        IndexName:=ColName+'1'; //Ӧ 
      end; 
      plAscend:=not plAscend; 
    end 
    else begin // 
      IndexName:=ColName+'2'; 
      plAscend:=false; 
      psIndexName:=ColName; 
    end; 
    except 
      on EDatabaseError do //δ½ 
      begin 
        Messagebeep(0); 
        //½ 
        IndexName:=''; 
        Close; 
        Exclusive:=true; 
        if mode='1' 
          then AddIndex(ColName+'1',ColName,[ixCaseInsensitive],'')// 
        else //'0' 
          AddIndex(ColName+'2',ColName,[ixDescending,ixCaseInsensitive],''); 
        Exclusive:=false; 
        Open; 
        try //try 1 
          if mode<>'1' 
          then begin 
            mode:='2';//ת 
            plAscend:=false; 
          end 
          else plAscend:=true; 
          IndexName:=ColName+mode; 
          psIndexName:=ColName; 
        except 
          on EDBEngineError do 
          IndexName:=''; 
        end //try 2 
      end 
    end; 
    First; 
  end; //with 
  DBGrid0.SelectedIndex:=iCol; 
end;//End of MySort 

    ѶпܵĴӦļ⼰ǱȽġˣѸù̷ӦĵԪУÿһDBGridֻҪݲͬDBGridColumnʵֶӦݱԶֻΪĳֶνһؼɣSecondery IndexesĽڳԶɣΪÿһֶһЩļ*.XG?,*YG?ȣȻбҪڱرǰеĸļɾ 

 DBGrid е Excel  ClipBoard 

  //ע:ķ ComObj, Excel97 Ԫ
  //----------------------------------------------------------- 
  // if toExcel = false, export dbgrid contents to the Clipboard 
  // if toExcel = true, export dbgrid to Microsoft Excel 
  procedure ExportDBGrid(toExcel: Boolean); 
  var 
    bm: TBookmark; 
    col, row: Integer; 
    sline: String; 
    mem: TMemo; 
    ExcelApp: Variant; 
  begin 
    Screen.Cursor := crHourglass; 
    DBGrid1.DataSource.DataSet.DisableControls; 
    bm := DBGrid1.DataSource.DataSet.GetBookmark; 
    DBGrid1.DataSource.DataSet.First; 
  
    // create the Excel object 
    if toExcel then 
    begin 
      ExcelApp := CreateOleObject('Excel.Application'); 
      ExcelApp.WorkBooks.Add(xlWBatWorkSheet); 
      ExcelApp.WorkBooks[1].WorkSheets[1].Name := 'Grid Data'; 
    end; 
  
    // First we send the data to a memo 
    // works faster than doing it directly to Excel 
    mem := TMemo.Create(Self); 
    mem.Visible := false; 
    mem.Parent := MainForm; 
    mem.Clear; 
    sline := ''; 
  
    // add the info for the column names 
    for col := 0 to DBGrid1.FieldCount-1 do 
      sline := sline + DBGrid1.Fields[col].DisplayLabel + #9; 
    mem.Lines.Add(sline); 
  
    // get the data into the memo 
    for row := 0 to DBGrid1.DataSource.DataSet.RecordCount-1 do 
    begin 
      sline := ''; 
      for col := 0 to DBGrid1.FieldCount-1 do 
        sline := sline + DBGrid1.Fields[col].AsString + #9; 
      mem.Lines.Add(sline); 
      DBGrid1.DataSource.DataSet.Next; 
    end; 
  
    // we copy the data to the clipboard 
    mem.SelectAll; 
    mem.CopyToClipboard; 
  
    // if needed, send it to Excel 
    // if not, we already have it in the clipboard 
    if toExcel then 
    begin 
      ExcelApp.Workbooks[1].WorkSheets['Grid Data'].Paste; 
      ExcelApp.Visible := true; 
    end; 
  
    FreeAndNil(mem); 
  //  FreeAndNil(ExcelApp); 
    DBGrid1.DataSource.DataSet.GotoBookmark(bm); 
    DBGrid1.DataSource.DataSet.FreeBookmark(bm); 
    DBGrid1.DataSource.DataSet.EnableControls; 
    Screen.Cursor := crDefault; 
  end;  

 
 2003-11-19 12:20:56    DBGridеcell??? 
//½һ,ڴϼһStringGrid

//unit1.pas

unit Unit1;

interface

uses
  Windows  Messages  SysUtils  Classes  Graphics  Controls  Forms  Dia

logs
  Grids;

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
    procedure StringGrid1DblClick(Sender: TObject);
    procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X  Y: Integer);
    procedure StringGrid1Click(Sender: TObject);

  private
    { Private declarations }

  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

const
  WeekDayName :Array[1..7] of String=('һ' 'ڶ' '' '
' '' '' '');

var
  X_Pos Y_Pos:integer;//ڴλ
  Col_Pos Row_Pos:integer;//Ԫλ

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
var
  i:integer;
begin
  Application.HintPause:=100;
  Font.Size :=10;
  Caption:='STringʯ';
  StringGrid1.ShowHint :=True;
  StringGrid1.ColCount :=8;
  StringGrid1.RowCount :=12;
  StringGrid1.Cells[0 0]:='18';
  for i:=1 to StringGrid1.ColCount -1  do
  StringGrid1.Cells[i 0]:=WeekDayName[i];
  for i:=1 to StringGrid1.RowCount -1 do
    StringGrid1.Cells[0 i]:=InttoStr(i+7)+':00';
  StringGrid1.Options :=StringGrid1.Options+[goTabs goROwSizing goColSizing]-[goEditing];
end;

procedure TForm1.StringGrid1DblClick(Sender: TObject);
var
  SchemeItem:String;
begin
  StringGrid1.MouseToCell(X_Pos Y_Pos Col_Pos Row_Pos) ;  //תλλ
  if (Col_Pos<0 )or (Row_Pos<0 ) then
    Exit;
  if (StringGrid1.Cells[Col_Pos Row_Pos]<>''  ) then //ȡƻҪ
  begin
    StringGrid1.Cells[Col_Pos Row_Pos]:='';
    Exit;
  end;
  SchemeItem:=InputBox('ʾ' 'ƻҪ:' '');
  StringGrid1.Cells[Col_Pos Row_Pos]:=SchemeItem;
End;

procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X  Y: Integer);
begin
  X_Pos:=x;
  Y_Pos:=y;
end;

procedure TForm1.StringGrid1Click(Sender: TObject);
begin
  StringGrid1.MouseToCell(X_Pos Y_Pos Col_Pos Row_Pos);//תԪλ
  StringGrid1.Hint :=StringGrid1.Cells[Col_Pos Row_Pos];//ʱøʾƻ
end;

end. 

 
 2003-11-19 12:33:15    ͷDBGridƼѧϰã 
   TclientDataSetؼDelphiƶֲʽݿĺĿؼDelphi3֣Delphi4Delphi5еõ˽һǿTclientDataSetؼǿĹܣǵ㡢C/SͶṹʹTclientDataSetؼborland˾ĹϿĹܻõǿҪTclientDataSetؼɫܡֶTDBGRIDؼʵָͷ

    ݿ¼ʱҪʵһЩͷͨҪõؼ⴦ʵ֡DelphiTClientDataSeADTֶͣTDbgridؼԷǳ׵ʵͷ

    һԱĹϢ˵岽衣
    ĳλĹϢĽṹͼʾ

              Ϣ


  Ա  |    |    |  ְ

    һµ Application,ڴһ TClientDataSet  TDataSource , name ԷֱΪ ClientDataSet1  DataSource1 , DataSource1  DataSource Ϊ ClientDataSet1 ϣһ TDBGRID  TdbNavigator ؼΪ DBGRID1  DbNavigator1 Datasource1 Ϊ ClientDataSet1

    Ȼ TclientDataSet ֶζ塣ֻζֶΣϢ͹ΪֶΣͼ3ʾֶηֱΪ INFO  Salary

    Ȼν INFO ֶκ SALARY ֶΣ۲ ChildDefsֶα༭ֶεֶΡȻ TclientDataSet Ŀݲ˵ TclientDataSet ؼȻһ꣩ CreateDataSet  CDS ݱļ TClientDataSet ֶΣTclientDataSet Ŀݲ˵ѡADD All Fields

    й ClientDataSet ϡ
     ClientDataSet ֮ҪDBGRIDʾԡҪ Colums йԣԣмɳͼ2ʾн档Ȼһ Tdbnavigator ؼ DataSource Ϊ Datasource1ЩͨĻBDEݿӦһģ 

 
 2003-11-19 13:33:24     dbgrid ʵ copypaste  
ϵCutCopyPasteٰť,ʹWindows±༭˵,¶ǷǳϤҲȱٵġDelphiеЩؼ,:TDBEditTDBImageTDBMemoTEdit,CutToClipboardCopyToClipboardPasteFromClipboard,Щؼ,⼸,ֻҪͨ򵥵ı,ͿʵٰťTDBGridؼȴṩ,޷ֱʵ⼸ֹܡڵݿӦó,TDBGridȴ(ֺ),ûCopyPaste,ʹв㡣ڱ̹,мؼСɡ,ӵʵ⼸ֹܡ

Ҫ˼·ȻTDBGridؼ޷ֱʵCopyPaste༭,ԽTDBGridؼҪ⼸ֱ༭ֶ(Field),תƵ߱⼸ֹܵĿؼ(TDBEditΪ)ȥ,༭Ϻ,ٴصTDBGridС

巽ƺõİTDBGridؼ(ΪDBGrid1)Ĵ,һTDBEdit(ΪDBEdit1)ؼ,DataSourcesΪDBGrid1DataSourcesͬ,DBGrid1ؼOnColEnter¼,ʹDBEdit1DataFieldֵDBGrid1ؼıѡֶεֶڴٰť:CopyPaste,ͼοѡDelphiĿ¼ImagesButtonsĿ¼Copy.bmpPaste.bmp
    CopyٰťOnClick¼:
DBEdit1.CopyToClipboard;

PasteٰťOnClick¼:
DBEdit1.PasteFromClipboard;
DBGrid1.SelectedField.AsString:=DBEdit1.Text;

ʱ,DBGrid1еĳһԪCellҪճһԪCell2Ĳֻȫ,굥ѡCell2,ʱDBEdit1ʾCell2ͬDBEdit1ҷѡ񲿷ֻȫ,Copyٰť;굥ѡCell,ʱDBEdit1ʾCellͬ,DBEditճղѡݵλò,Pasteٰť,ղѡݲ뵽λ,CellҲ֮ıɲ,ɴһCopyPaste

ַʵCopyPaste,Ĳһļƶظݲ,Ҳ߼ܿ,ʵCopyPasteķ,ƺ󡣵ӦóʹЩûĳֿ뼼ɡпܻʹƴ뷨,ʹ߶CopyPasteͲ(оַĲϳ),ַǳһͬ﷭ȥѰҵĻ,⻹һֲķλTDBGridʵֳCopyPasteķ,벻ߴͽ̡

йصĳ:
procedure TUnitDetail.DBGrid1ColEnter(Sender:TObject);
begin
  case DBGrid1.SelectedIndex of
   0:DBEdit1.DataField:='UnitNum';
     1:DBEdit1.DataField:='UnitName';
   2:DBEdit1.DataField:='Header';
   3:DBEdit1.DataField:='Address';
   4:DBEdit1.DataField:='Tel';
  end;
end;


procedure TUnitDetail.SBCopyClick(Sender:TObject);
begin
   DBEdit1.CopyToClipboard;
end;

procedureTUnitDetail.SBPasteClick(Sender:TObject);
begin
   DBEdit1.PasteFromClipboard;
   DBGrid1.SelectedField.AsString:=DBEdit1.text;
end;  

 
 2003-11-19 13:34:33    ֹDBGridаdeleteɾ¼ 
procedure TForm1.DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); 
begin 
  if (ssctrl in shift) and (key=vk_delete) then key:=0; 
end; 

 
 2003-11-19 13:39:54     DBGrid  
һӣҪעǣһʼҪѯֶȫTDBGridУзʳͻġ

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, Grids, DBGrids, StdCtrls, ExtCtrls, DBCtrls;

type
  TTFm_Main = class(TForm)
    qry_Data: TQuery;
    Ds_Data: TDataSource;
    Ed_Search: TEdit; //һTEdit.
    dbg_Data: TDBGrid;
    Database1: TDatabase; //ݿ⹹ʱ趨
    DBNavigator1: TDBNavigator;
    procedure dbg_DataTitleClick(Column: TColumn);
    procedure FormCreate(Sender: TObject);
    procedure Ed_SearchChange(Sender: TObject);

  private
  { Private declarations }
    FQueryStatement: string; // SQL ѯ䡣
    FALphaNumericKeyPress: TKeyPressEvent;

  public
  { Public declarations }
    property QueryStatement: string read FQueryStatement;
    procedure FloatOnKeyPress(Sender: TObject; var Key: Char);
  end;

var
  TFm_Main: TTFm_Main;

implementation

{$R *.DFM}

procedure TTFm_Main.dbg_DataTitleClick(Column: TColumn);
var
  vi_Counter: Integer;
  vs_Field: string;
begin
  with dbg_Data do
  begin

  //First, deselect all the Grid Columns
    for vi_Counter := 0 to Columns.Count - 1 do
      Columns[vi_Counter].Color := clWindow;

  //Next "Select" the column the user has Clicked on
    Column.Color := clTeal;

  //Get the FieldName of the Selected Column
    vs_Field := Column.FieldName;

  //Order the Grid Data by the Selected column
    with qry_Data do
    begin
      DisableControls;
      Close;
      SQL.Clear;
      SQL.Text := QueryStatement + ' ORDER BY ' + vs_Field;
      Open;
      EnableControls;
    end;
  //Get the DataType of the selected Field and change the Edit event

  //OnKeyPress to the proper method Pointer
    case Column.Field.DataType of
      ftFloat: Ed_Search.OnKeyPress := FloatOnKeyPress;
    else
      Ed_Search.OnKeyPress := FALphaNumericKeyPress;
    end;
  end;
end;

procedure TTFm_Main.FloatOnKeyPress(Sender: TObject; var Key: Char);
begin
  if not (Key in ['0'..'9', #13, #8, #10, #46]) then
    Key := #0;
end;

procedure TTFm_Main.FormCreate(Sender: TObject);
begin

  //Keep a pointer for the default event Handler
  FALphaNumericKeyPress := Ed_Search.OnKeyPress;

  //Set the original Query SQL Statement
  FQueryStatement := 'SELECT * FROM your_table_name';

  //Select the first Grid Column
  dbg_DataTitleClick(dbg_Data.Columns[0]);
end;

procedure TTFm_Main.Ed_SearchChange(Sender: TObject);
var
  vi_counter: Integer;
  vs_Field: string;
begin
  try
    with dbg_Data do
    begin

  //First determine wich is the Selected Column
      for vi_Counter := 0 to Columns.Count - 1 do
        if Columns[vi_Counter].Color = clTeal then
        begin
          vs_Field := Columns[vi_Counter].FieldName;
          Break;
        end;

  //Locate the Value in the Query
      with qry_Data do
        case Columns[vi_Counter].Field.DataType of
          ftFloat: Locate(vs_Field, StrToFloat(Ed_Search.Text),
              [loCaseInsensitive, loPartialKey]);
        else
          Locate(vs_Field, Ed_Search.Text, [loCaseInsensitive, loPartialKey]);
        end;
    end;
  except
  end;
end;

end. 

 
 2003-11-19 13:53:23    ԶӦ 
///////Դ뿪ʼ
uses
  Math;

function DBGridRecordSize(mColumn: TColumn): Boolean;
{ ؼ¼ʾǷɹ }
begin
  Result := False;
  if not Assigned(mColumn.Field) then Exit;
  mColumn.Field.Tag := Max(mColumn.Field.Tag,
    TDBGrid(mColumn.Grid).Canvas.TextWidth(mColumn.Field.DisplayText));
  Result := True;
end; { DBGridRecordSize }

function DBGridAutoSize(mDBGrid: TDBGrid; mOffset: Integer = 5): Boolean;
{ ԶӦǷɹ }
var
  I: Integer;
begin
  Result := False;
  if not Assigned(mDBGrid) then Exit;
  if not Assigned(mDBGrid.DataSource) then Exit;
  if not Assigned(mDBGrid.DataSource.DataSet) then Exit;
  if not mDBGrid.DataSource.DataSet.Active then Exit;
  for I := 0 to mDBGrid.Columns.Count - 1 do begin
    if not mDBGrid.Columns[I].Visible then Continue;
    if Assigned(mDBGrid.Columns[I].Field) then
      mDBGrid.Columns[I].Width := Max(mDBGrid.Columns[I].Field.Tag,
        mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption)) + mOffset
    else mDBGrid.Columns[I].Width :=
      mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption) + mOffset;
    mDBGrid.Refresh;
  end;
  Result := True;
end; { DBGridAutoSize }
///////Դ

///////ʹʾʼ
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  DBGridRecordSize(Column);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  DBGridAutoSize(DBGrid1);
end;
///////ʹʾ 

 
 2003-11-19 13:55:47    ƳDBGridĴֱοжGridǷй 
type
  TNoVertScrollDBGrid = class(TDBGrid)
  protected
    procedure Paint; override;
  end;

procedure Register;

implementation

procedure TNoVertScrollDBGrid.Paint;

begin
  SetScrollRange(Self.Handle, SB_VERT, 0, 0, False);
  inherited Paint;
end;

procedure Register;
begin
  RegisterComponents('Data Controls', [TNoVertScrollDBGrid]);
end;

end. 

 
DBGridϷŵӣͬʱοTDBGridؼʵϷŵһ˼·/DBGridDrag & DropϷţ 
unit GridU1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Dialogs, Db, DBTables, Grids, DBGrids, StdCtrls;

type
  TForm1 = class(TForm)
    MyDBGrid1: TDBGrid;
    Table1: TTable;
    DataSource1: TDataSource;
    Table2: TTable;
    DataSource2: TDataSource;
    MyDBGrid2: TDBGrid;
    procedure MyDBGrid1MouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure MyDBGrid1DragOver(Sender, Source: TObject;
      X, Y: Integer; State: TDragState; var Accept: Boolean);
    procedure MyDBGrid1DragDrop(Sender, Source: TObject;
      X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

var
  SGC : TGridCoord;

procedure TForm1.MyDBGrid1MouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  DG : TDBGrid;
begin
  DG := Sender as TDBGrid;
  SGC := DG.MouseCoord(X,Y);
  if (SGC.X > 0) and (SGC.Y > 0) then
    (Sender as TDBGrid).BeginDrag(False);
end;

procedure TForm1.MyDBGrid1DragOver(Sender, Source: TObject; 
  X, Y: Integer; State: TDragState; var Accept: Boolean);
var
  GC : TGridCoord;
begin
  GC := (Sender as TDBGrid).MouseCoord(X,Y);
  Accept := Source is TDBGrid and (GC.X > 0) and (GC.Y > 0);
end;

procedure TForm1.MyDBGrid1DragDrop(Sender, Source: TObject;
  X, Y: Integer);
var
  DG     : TDBGrid;
  GC     : TGridCoord;
  CurRow : Integer;
begin
  DG := Sender as TDBGrid;
  GC := DG.MouseCoord(X,Y);
  with DG.DataSource.DataSet do begin
    with (Source as TDBGrid).DataSource.DataSet do
      Caption := 'You dragged "'+Fields[SGC.X-1].AsString+'"';
    DisableControls;
    CurRow := DG.Row;
    MoveBy(GC.Y-CurRow);
    Caption := Caption+' to "'+Fields[GC.X-1].AsString+'"';
    MoveBy(CurRow-GC.Y);
    EnableControls;
  end;
end;

end. 

 
 2003-11-24 11:03:41    dbgridƶһְ취 
ؼ,ҲøĿؼ!ֱӌɫaּӵĴwΟoо.
type
 TDBGrid = class(DBGrids.TDBGrid)
 private
  FOldGridWnd : TWndMethod;
  procedure NewGridWnd (var Message : TMessage);
 public
  constructor Create(AOwner: TComponent); override;
 end;
 TXXXForm = class(TForm)
  ......
 end;
 { TDBGrid }


constructor TDBGrid.Create(AOwner: TComponent);
begin
 inherited;
 Self.FOldGridWnd := Self.WindowProc;
 Self.WindowProc :=  NewGridWnd;
end;

procedure TDBGrid.NewGridWnd(var Message: TMessage);
var
 IsNeg : Boolean;
begin

if Message.Msg = WM_MOUSEWHEEL then
 begin
  IsNeg := Short(Message.WParamHi) < 0;
  if IsNeg then
   self.DataSource.DataSet.MoveBy(1)
  else
   self.DataSource.DataSet.MoveBy(-1)
 end
 else Self.FOldGridWnd(Message);

end;



TDBGrid = class(DBGrids.TDBGrid)
....
end;
 һҪǰ,ҲԌtɫִaһÆΟo,
Ȼuses publicunit;
ټ@һ:
TDBGrid = Class(publicunit.TDBGrid); 
TXXFrom =Class(TForm)   

 
 2003-11-25 17:29:59    ޸ĹGridsַ֧ҳĹܡ 
   /delphi/source/vclĿ¼¾ʹáõD7Ͱ汾ѻȿʹãԷ⡣ 

޸ĹGridsַ֧ҳĹܡ 
 
 2003-12-1 10:29:21    ַ֧ҳĹܵGrids 
   ϸ˵ڡ 

ַ֧ҳĹܵGrids 
 
 2003-12-9 10:34:26    DBGridбƱȽ 
һDBGrid      
     DBGrid ʵбú DBGrid иֶε PickList ַбʼֵ DropDownRows ɡְϢеļֶΣַͣΪƲ£
    1ڴϷ Table1DataSource1DBGrid1DBNavigator1 ȿؼ󣬰±ø:

---------------------------------------
                     趨ֵ
---------------------------------------
Table1         DataBase      sy1
               TableName     zgk.dbf //ְϢ
               DataSource1   DataSet Table1
DbGrid1        DataSource    DataSource1
DBNavigator1   DataSource    Datasource1
-------------------------------------------

    2˫ Table1ڵ Form1.Table1 УҼݲ˵ Add Fields ˵ѡеֶκ󣬰 OK ť

    3޸ĵ 2 ֶε DisplayLabel ԡ Table1ZGBH ֶΪ  Object Inspector ѡ Table1ZGBH޸ DisplayLabel= ְţֶơ
 
    4˫ DBGrid1ڵ Editing DBGrid1.Columns У  Add all Fields ť Table1 ֶΡ

    5 Editing DBGrid1.Columns ڣѡ jg һУл Object Inspector ڣ޸ PickList.Strings Ϊ
֦
  
  ƽɽ
  㽭С

    6 Form1.Oncreate ¼д䣺

    Table1.Open;

    7F9 Уĳ¼ļֶΣұ߼һťťɳһб 5 ַѡ񡣵ȻҲһбеַ


DBGrid      
    νֶ(LookUp Field) DBGridеĳؼֶεֵԴһݿӦֶΡòֶμЧı󣬶 DBGrid ʾʽΪԲʾؼֶΣʾԴݿӦһֶεݡ

    磬 DBGrid ʾͱ༭ְϢְšְᡢڵλţλԴһݿ񡪡λ⣬ơλšΪؼֶΡֱʾͱ༭λŵĻ 123 ȷǳֱ۵֣༭ʱ׳ʾͱ༭ǵλжӦĵλƻǳֱۡ DBGrid ֵ֧Ĳֶδĺô

    ʵ DBGrid ĲֶͬҪκ䣬Ʋ£
    1ڴϷ Table1Table2DataSource1DBGrid1DBNavigator1 ȿؼ󣬰±ø:
---------------------------------------
                 趨ֵ
---------------------------------------
Table1       DataBase    sy1
             TableName   zgk.dbf //ְϢ
Table2       DataBase    sy1
             TablenAME   dwk.dbf //λϢ
DataSource1  DataSet     Table1
DbGrid1      DataSource  DataSource1
DBNavigator1 DataSource  Datasource1
------------------------------------------

    2˫ Table1ڵ Form1.Table1 УҼݲ˵ Add Fields ˵ѡеֶκ󣬰 OK ť

    3޸ĵ 2 ֶε DisplayLabel ԡ Table1ZGBH ֶΪ Object Inspector ѡ Table1ZGBH޸ DisplayLabel= ְţֶơ

    4 Table1DWBH.Visible=False

    5 Form1.Table1 ڣҼݲ˵ New Field ˵һֶ DWMCڵĴӦԣ OK ťȷϣ Object Inspector ڣ Table1DWMC.DisplayLabel= λơ

     6 Form1.Oncreate ¼д䣺
     Table1.Open;

     7 F9 Уĳ¼ĵλֶʱֶΣһбұߵ¼ͷбнѡԿбڵλϢ⣬Ҳݡ


    DBGrid ебͲֶε
    Ȼ DBGrid ебͲֶΣбʽֵģкܴĲ

    1 PickList õбֹģȻҲڳ޸ģ̬ȻֱݿȡݵĲֶΡ

    2 PickList õб벻беݣֶֻԴݿйؼֶеݣܱ֤ݵԡ

    3 PickList õбƽΪ򵥡 

 
 2003-12-10 14:44:11     dbgrid  dbgrideh ʾԶ 
procedure TForm1.Timer1Timer(Sender: TObject);
var
m:tmessage;
begin
 m.Msg:=WM_VSCROLL;
 m.WParamLo:=SB_LINEDOWN;
 m.WParamHi:=1 ;
 m.LParam:=0;
 postmessage(self.DBGrid1.Handle,m.Msg,m.WParam,m.LParam);

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
self.Timer1.Enabled:=true;
end;  

ҪԶϵشͷβ´
if table1.Eof then table1.First;   

 
 2003-12-10 14:58:31    DBGrid Էǲֶεγ CheckBox ѡ 
ɽdbgriddatasetʾֶΪʽֶΣOnGetText¼д´룺
table
procedure TForm1.Table1Myfield1GetText(Sender: TField;
 var Text: String; DisplayText: Boolean);
var Pd:string;
begin
 inherited;
 pd:=table1.fieldbyname('myfield1').asstring;
 if pd='1' then
     Text:=''
 else
     if pd='2' then
        text:=''
     else
        Text:='';
end; 

 
 2003-12-15 9:22:15    DbGridؼػʾ 
DbGridؼػʾ

  1 ½һĹ(1ǲ˵󣬵2 DbGridؼ):
    Procedure ViewTitle(Sender:TObject;DbgColumns:TDBGrid);
    //ػʾDbGrid

  2 ȻCtrl+Shift+Cϼ,Ĺ̻ʵֲֳ֡
    Procedure FrmStock.ViewTitle(Sender:TObject;DbgColumns:TDBGrid);
    begin
      With (Sender as TMenuItem) do
      begin
        Checked:=not Checked;
        DbgColumns.Columns[Tag].Visible:=Checked;
      end;
    end;

  3 Ѳ˵TagóɸDbGridColumnsֵӦ,:
    DbGridһǡڡڵ0,ȻҪеĲ˵Tagó0

  4 Ѳ˵OnClick¼ѡViewTitleù̡ 

 
 2003-12-16 11:48:15    й˫dbgrid⣨û˫dbgirdؼĳһֶʱ,˫ͽ....?DFWDouZheng 
procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var
 temp, title: string;
begin
 temp := Column.FieldName;
 qusp.Close;
 if Column.Index <> lastcolumn then
 begin
   if (Pos('', DBGrid1.Columns[LastColumn].Title.Caption) > 0) or (Pos('', DBGrid1.Columns[LastColumn].Title.Caption) > 0) then
     DBGrid1.Columns[LastColumn].Title.Caption := Copy(DBGrid1.Columns[LastColumn].Title.Caption, 3, Length(DBGrid1.Columns[LastColumn].Title.Caption) - 2);
   qusp.Sql[icount] := 'order by ' + temp + ' asc';
   DBGrid1.Columns[Column.Index].Title.Caption := '' + DBGrid1.Columns[Column.Index].Title.Caption;
   lastcolumn := column.Index;
 end
 else
 begin
   LastColumn := Column.Index;
   title := DBGrid1.Columns[LastColumn].Title.Caption;
   if Pos('', title) > 0 then
   begin
     qusp.Sql[icount] := 'order by ' + temp + ' desc';
     Delete(title, 1, 2);
     DBGrid1.Columns[LastColumn].Title.Caption := '' + title;
   end
   else if Pos('', title) > 0 then
   begin
     qusp.Sql[icount] := 'order by ' + temp + ' asc';
     Delete(title, 1, 2);
     DBGrid1.Columns[LastColumn].Title.Caption := '' + title;
   end
   else
   begin
     qusp.Sql[icount] := 'order by ' + temp + ' asc';
     DBGrid1.Columns[LastColumn].Title.Caption := '' + title;
   end;
 end;
 qusp.Open;
end; 

 
 2003-12-16 17:02:46    DBGridУܵһԪѡУֿԱ༭Ԫأhongxing_dl ṩ롿 
   ƹУʱݽϴfield ϶ʱֻǵԪܻĳfieldݴУΪ˲Ż뵽⣬취£
    Ԫ͸ĵǰɫ취Ҳû취İ취ɣ

type
 TMyDBGrid=class(TDBGrid);
//////////////////////////////////
//DBGrid1.Options->dgEditing=True
//DBGrid1.Options->dgRowSelect=False
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
 DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
 with TMyDBGrid(Sender) do
 begin
   if DataLink.ActiveRecord=Row-1 then
   begin
     Canvas.Font.Color:=clWhite;
     Canvas.Brush.Color:=$00800040;
   end
   else
   begin
     Canvas.Brush.Color:=Color;
     Canvas.Font.Color:=Font.Color;
   end;
   DefaultDrawColumnCell(Rect,DataCol,Column,State);
 end;
end; 

ͨd7 

 
 2003-12-17 13:52:49    DbGridߣʵEXCELԶţЩ޹. 
Ǻǣ Grid ؼǿ hongxing_dlĴ루Խ⣩

unit Unit1;

interface

uses
 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
 Grids, DBGrids, StdCtrls, Buttons, Db, DBTables, ExtCtrls, jpeg;
const ROWCNT=20;

type
    tmygrid=class(tdbgrid)
    protected
      procedure Paint;override;
      procedure DrawCell(ACol:Integer;ARow:Integer;ARect:TRect;AState:TGridDrawState);override;
    public
      constructor create(AOwner:TComponent);override;
      destructor  destroy;override;
    end;

 TForm1 = class(TForm)
   BitBtn1: TBitBtn;
   DataSource1: TDataSource;
   Table1: TTable;
   procedure BitBtn1Click(Sender: TObject);
 private
   { Private declarations }
 public
   { Public declarations }
 end;

var
 Form1: TForm1;
 mygrid:tmygrid;
implementation

{$R *.DFM}

    {tmygrid}
    constructor tmygrid.create(AOwner:TComponent);
    begin
       inherited create(Owner);
       RowCount:=ROWCNT;
    end;

    destructor tmygrid.destroy;
    begin
      inherited;
    end;

    procedure tmygrid.Paint;
    begin
      RowCount:=ROWCNT;
      if dgIndicator in options then
         ColWidths[0]:=30;
      inherited;
    end;

    procedure tmygrid.DrawCell(ACol:Integer;ARow:Integer;ARect:TRect;AState:TGridDrawState);
    begin
      inherited;
      if (ARow>=1) and (ACol=0) then
         Canvas.TextRect(ARect,ARect.Left,ARect.Top,IntToSTr(ARow));
   end;

procedure TForm1.BitBtn1Click(Sender: TObject);
begin
 mygrid:=tmygrid.create(Self);
 mygrid.parent:=self;
 mygrid.left:=0;
 mygrid.top:=0;
 mygrid.Height:=300;
 mygrid.DataSource:=DataSource1;
end;

end. 

 
 2003-12-22 9:22:15    νDBGRIDݵͬһEXCELУ 
ǰԣ

ʵУΪʡɱͿڣһЩԱͨDBGridеֱӵExcelУǰܿĺֻWorkBookһSheetеݣֶ֧Sheet

ԪӦã

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, DBTables, Grids, DBGrids, ActiveX, ComObj,
Excel2000, OleServer;

Ի

OSWin2k ProExcel2kDelphi6.0

Դ򣺡

{
DBGridExcelֶ֧Sheet
ƣCoolSlob
ڣ2002-10-23
֧֣CoolSlob@163.com
øʽCopyDbDataToExcel([DBGrid1, DBGrid2]);
}

procedure CopyDbDataToExcel(Args: array of const);
var
  iCount, jCount: Integer;
  XLApp: Variant;
  Sheet: Variant;
  I: Integer;
begin
  Screen.Cursor := crHourGlass;
  if not VarIsEmpty(XLApp) then
  begin
    XLApp.DisplayAlerts := False;
    XLApp.Quit;
    VarClear(XLApp);
  end;

  try
    XLApp := CreateOleObject(Excel.Application);
  except
    Screen.Cursor := crDefault;
  Exit;
  end;

  XLApp.WorkBooks.Add;
  XLApp.SheetsInNewWorkbook := High(Args) + 1;

  for I := Low(Args) to High(Args) do
  begin
    XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args[I].VObject).Name;
    Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args[I].VObject).Name];

    if not TDBGrid(Args[I].VObject).DataSource.DataSet.Active then
    begin
      Screen.Cursor := crDefault;
      Exit;
    end;

    TDBGrid(Args[I].VObject).DataSource.DataSet.first;
    for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do
      Sheet.Cells[1, iCount + 1] := TDBGrid(Args[I].VObject).Columns.Items[iCount].Title.Caption;

    jCount := 1;
    while not TDBGrid(Args[I].VObject).DataSource.DataSet.Eof do
    begin
      for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do
        Sheet.Cells[jCount + 1, iCount + 1] := TDBGrid(Args[I].VObject).Columns.Items[iCount].Field.AsString;

      Inc(jCount);
      TDBGrid(Args[I].VObject).DataSource.DataSet.Next;
    end;
  end;

  XlApp.Visible := True;
  Screen.Cursor := crDefault;
end; 

 
 2003-12-22 9:25:32    DbGridؼı˵ 
DbGridؼı˵

procedure TFrmOrderPost.DbgOrderPostMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  CurPost:TPoint;
begin
  GetCursorPos(CurPost);//굱ǰ
  if (y<=17) and (x<=vCurRect.Right) then
  begin
    if button=mbright then
    begin
      PmTitle.Popup(CurPost.x,CurPost.y);
    end;
  end;
end; 
//vCurRectñDbGridDrawColumnCell¼л
{procedure TFrmOrderPost.DbgOrderPostDrawColumnCell(Sender: TObject;const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin 
  vCurRect:=Rect;//vCurRectʵֲֶ
end;} 

 
 2003-12-22 10:12:55    DbGridؼı˵ 
DbGridؼı˵

procedure TFrmOrderPost.DbgOrderPostMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  CurPost:TPoint;
begin
  GetCursorPos(CurPost);//굱ǰ
  if (y<=17) and (x<=vCurRect.Right) then
  begin
    if button=mbright then
    begin
      PmTitle.Popup(CurPost.x,CurPost.y);
    end;
  end;
end; 
//vCurRectñDbGridDrawColumnCell¼л
{procedure TFrmOrderPost.DbgOrderPostDrawColumnCell(Sender: TObject;const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin 
  vCurRect:=Rect;//vCurRectʵֲֶ
end;} 

 
 2003-12-22 10:14:26    DBGridExcelֶ֧Sheet 
{
DBGridExcelֶ֧Sheet
øʽCopyDbDataToExcel([DBGrid1, DBGrid2]);
}
procedure CopyDbDataToExcel(Args: array of const);
var
  iCount, jCount: Integer;
  XLApp: Variant;
  Sheet: Variant;
  I: Integer;
begin
  Screen.Cursor := crHourGlass;
  if not VarIsEmpty(XLApp) then
  begin
    XLApp.DisplayAlerts := False;
    XLApp.Quit;
    VarClear(XLApp);
  end;

  try
    XLApp := CreateOleObject(Excel.Application);
  except
    Screen.Cursor := crDefault;
    Exit;
  end;

  XLApp.WorkBooks.Add;
  XLApp.SheetsInNewWorkbook := High(Args) + 1;

  for I := Low(Args) to High(Args) do
  begin
    XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args[I].VObject).Name;
    Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args[I].VObject).Name];

    if not TDBGrid(Args[I].VObject).DataSource.DataSet.Active then
    begin
      Screen.Cursor := crDefault;
      Exit;
    end;

    TDBGrid(Args[I].VObject).DataSource.DataSet.first;
    for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do
      Sheet.Cells[1, iCount + 1] :=
    TDBGrid(Args[I].VObject).Columns.Items[iCount].Title.Caption;

    jCount := 1;
    while not TDBGrid(Args[I].VObject).DataSource.DataSet.Eof do
    begin
      for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do
        Sheet.Cells[jCount + 1, iCount + 1] :=
      TDBGrid(Args[I].VObject).Columns.Items[iCount].Field.AsString;

      Inc(jCount);
      TDBGrid(Args[I].VObject).DataSource.DataSet.Next;
    end;
    XlApp.Visible := True;
  end;
  Screen.Cursor := crDefault;
end; 

 
 2004-1-2 11:26:02    ƾõDBGrid´塿 
   ôļɺͷشδһֳ嶯ɣԼһDBGridͽһDBGridķ

    DelphiеTDBGridһʹƵʺܸߵVCLԪTDBGridԣݰ󶨵ģܹ幦ǿֶΣ¼ḻȣرʹ÷ǳ򵥡ǣFoxProVB PBеDBGridȾͻ֣ᷢTDBGridҲԵȱݣļ̲ʽǳáȻܶ˶̰ͨѻسתTabĽTDBGrid뷽ʽȻܺܺõؽ⣬ΪʲôأĽȱݵĸԭзڴ˻һ뼫㡢ExcelDBGridProԪ

     DBGridĸӣCell״̬״̬꣬룬״̬A1״̬бѡ񣬼״̬A2״̬û꣬룬״̬Bʾ״̬룬״̬CDBGridܵĿƼлسTabEscԼݴ˿ԻÿCell״̬תͼ

    ѿûƶ뽹ʱԲͬƶҪòͬĲܱʹöͬļһбҪбƶʱΪԡˣѵĸԭ״̬ͼڸӺͲһ¡ʶǿԶDBGrid죺

    1ȻB״̬ǺģӦȥζŽÿһµCell༭״̬Ҫٰسˡÿ״̬BCellҪ»ƣǿڻƶжǷ״̬ΪgdFocusedCellEditorModeΪ档ֵעǣTDBGridCellĺDefaultDrawColumnCell麯˲̳ͨиıΪֻʹṩ¼OnDrawColumnCellһЩDBGridProУһͨʵʾ¼OnDrawColumnCellʵֵġһⲿͲʹø¼ˣṩһOnOwnDrawColumnCell¼еCreateDefaultDrawColumnCell

    2ƼӦü򻯣ÿƼDBGridProУǿ˷ͻسĹܣĩλʱ񣻻سܺƶ뽹㣬һܵб3ʵַϣü¼APIkeybd_eventƼתTDBGridĿƼڱ༭״̬лسȡ¼·һTab¼⵽ҷʱͨ༭EM_CHARFROMPOSϢжϱ༭еĹλãԾǷӦ񡣼еDoKeyUped

    3Cell뷽ʽDBGridProУûûسбַʽܻɵĻسܵĻֻҪõû÷ǳ㣺͵Cell֮ûֱӼ޸ģ򰴻سһ񣻷򵯳бѡٰ֮سʱرбһ񡣼еDoKeyUpedDefaultDrawColumnCell

    һ֮ûѾǳˣִµ⣺TDBGridУûͨȵCell֪ܿDBGridProиCellûܺѷ뽹㣡һķExcelһڽλôһڿ--һǿʵֵģͼ2

    WindowsṩһAPIڴϽɽ¼RegionRegionԲͬķʽӶõ""ڣĴڡDBGridProܡڲһɫPanelȻÿĵRegion""뽹CellϣûܿһĿı߿ˡ

    ¶ĥֳµ⣺Columnλûȸıʱ߿ͬ仯¼Ȼȫ⣬ΪڳҲColumnĿȣ¼OnDrawColumnCellҲܽȸıʱ¼˵ǣTDBGridеʵһTDBGridInplaceEdit̳TInplaceEditܼ⵽TDBGridInplaceEditʲôʱıСλãͿñ߿ҲŸıˡҪʵһ㣬һTDBGridInplaceEdit̳еġWM_WINDOWPOSCHANGEDϢ滻ԭTDBGridInplaceEdit򵥵İ취ͨ鿴Դ뷢֣CreateEditorģǸ麯--TDBGridԸֻҪǴTInplaceEdit͵ġģʽĽǶƷΪ""Factory MethodʹһʵӳٵࡣǵĿľҪﵽˡ

    ҵǣTDBGridInplaceEditDBGrids.pasжimplementУⲿļ޷䶨ˣ˳ǰĴȫһ飬ֱ޸DBGrids.pasļȻǰ߲ȡֻ汾⣩ǲܴTDBGridInplaceEdit̳еġѵûкð취𣿵ȻУǿTDBGridInplaceEditĿɶдWindowProcWM_WINDOWPOSCHANGEDϢWindowProcʵһָ룬ָĺôԪϢǣǿCreateEditorнTDBGridInplaceEditWndProc滻ԼʵֵĹҺָ룬Ӷʵֺ̳ͬĹܡȱƻķװԣΪǲòDBGridProдTDBGridInplaceEditĹȻܻõķӭ顣

    ˣTDBGridѾһ㡢۵DBGridProˣǿ԰עVCLԪʹáԴ룺


unit DBGridPro;

interface

uses
  Windows, Messages, SysUtils, Classes, Controls, Grids, DBGrids, ExtCtrls, richEdit, DBCtrls, DB;

type TCurCell = Record {ǰCellλ}
  X : integer; {нCellColumnIndex}
  Y : integer; {нCellڵļ¼ļ¼}
  tag : integer; {CellǷ񵯳б}
  r : TRect; {ûʹ}
end;

type
  TDBGridPro = class(tcustomdbgrid)
  private
    hr,hc1 : HWND; {Region Handle}
    FPan : TPanel; {ʾڿõPanel}
    hInplaceEditorWndProc : TWndMethod; {༭ԭWindowProc}
    {ҵ༭WindowProc}
    procedure InPlaceEditorWndProcHook(var msg : TMessage);
    procedure AddBox; {ʾ߿}
    {ʵTCustomDBGridOnDrawColumnCell¼}
    procedure DoOwnDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
    {¼}
    procedure DoKeyUped(Sender: TObject; var Key: Word; Shift: TShiftState);

  protected
    curCell : TCurCell; {¼ǰнCell}
    FOwnDraw : boolean; {TCustomDBGrid.DefaultDrawing}
    FOnDraw : TDrawColumnCellEvent; {TCustomDBGrid.OnDrawColumnCell}
    function CreateEditor : TInplaceEdit; override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    procedure DefaultDrawColumnCell(const Rect: TRect;DataCol: Integer; Column: TColumn; State: TGridDrawState); overload;

  public
    constructor Create(AOwner : TComponent); override;
    destructor Destroy; override;

  published
    property Align;
    property Anchors;
    property BiDiMode;
    property BorderStyle;
    property Color;
    property Columns stored False; //StoreColumns;
    property Constraints;
    property Ctl3D;
    property DataSource;
    property OwnDraw : boolean read FOwnDraw write FOwnDraw default false;
    property DragCursor;
    property DragKind;
    property DragMode;
    property Enabled;
    property FixedColor;
    property Font;
    property ImeMode;
    property ImeName;
    property Options;
    property ParentBiDiMode;
    property ParentColor;
    property ParentCtl3D;
    property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property ReadOnly;
    property ShowHint;
    property TabOrder;
    property TabStop;
    property TitleFont;
    property Visible;
    property OnCellClick;
    property OnColEnter;
    property OnColExit;
    property OnColumnMoved;
    property OnDrawDataCell; { obsolete }
    property OnOwnDrawColumnCell : TDrawColumnCellEvent read FOnDraw write FOnDraw;
    property OnDblClick;
    property OnDragDrop;
    property OnDragOver;
    property OnEditButtonClick;
    property OnEndDock;
    property OnEndDrag;
    property OnEnter;
    property OnExit;
    property OnKeyup;
    property OnKeyPress;
    property OnKeyDown;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnStartDock;
    property OnStartDrag;
    property OnTitleClick;
end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Data Controls', [TDBGridPro]);
end;

{ TDBGridPro }
procedure TDBGridPro.AddBox;
var
  p,p1 : TRect;
begin
  GetWindowRect(InPlaceEditor.Handle,p);
  GetWindowRect(FPan.Handle,p1);
  if (p.Left=p1.Left) and (p.Top=p1.Top) and (p.Right=p1.Right) and (p.Bottom=p1.Bottom) then exit;
  if hr<>0 then DeleteObject(hr);
  if hc1<>0 then DeleteObject(hc1);
 {Region}
  hr := CreateRectRgn(0,0,p.Right-p.Left+4,p.Bottom-p.Top+4);
  hc1:= CreateRectRgn(2,2,p.Right-p.Left+2,p.Bottom-p.Top+2);
  {ϳɿRegion}
  CombineRgn(hr,hc1,hr,RGN_XOR);
  SetWindowRgn(FPan.Handle,hr,true);
  FPan.Parent := InPlaceEditor.Parent;
  FPan.ParentWindow := InPlaceEditor.ParentWindow;
  FPan.Height := InPlaceEditor.Height+4;
  FPan.Left := InPlaceEditor.Left-2;
  FPan.Top :=InPlaceEditor.Top-2;
  FPan.Width := InPlaceEditor.Width+4;
  FPan.BringToFront;
end;

constructor TDBGridPro.Create(AOwner: TComponent);
begin
  inherited;
  {Ϊ߿Panel}
  FPan := TPanel.Create(nil);
  FPan.Parent := Self;
  FPan.Height := 0;
  FPan.Color := 0;
  FPan.Ctl3D := false;
  FPan.BevelInner := bvNone;
  FPan.BevelOuter := bvNone;
  FPan.Visible := true;
  DefaultDrawing := false;
  OnDrawColumnCell := DoOwnDrawColumnCell;
  OnOwnDrawColumnCell := nil;
  curCell.X := -1;
  curCell.Y := -1;
  curCell.tag := 0;
  hr := 0;
  hc1 := 0;
end;

function TDBGridPro.CreateEditor: TInplaceEdit;
begin
  result := inherited CreateEditor;
  hInPlaceEditorWndProc := result.WindowProc;
  result.WindowProc := InPlaceEditorWndProcHook;
end;

procedure TDBGridPro.DefaultDrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  {Ҫ㣬DBGrid༭״̬}
  if (gdFocused in State) then
  begin
    EditorMode := true;
    AddBox;
    {ǽһµCellȫѡеַ}
    if (curCell.X <> DataCol) or (curCell.Y <> DataSource.DataSet.RecNo)
    then begin
      curCell.X := DataCol;
      curCell.Y := DataSource.DataSet.RecNo;
      curCell.tag := 0;
      GetWindowRect(InPlaceEditor.Handle,curCell.r);
      SendMessage(InPlaceEditor.Handle,EM_SETSEL,0,1000);
    end;
    end else {ʾ״̬Cell}
  TCustomDBGrid(Self).DefaultDrawColumnCell(Rect,DataCol,Column,State);
  end;

destructor TDBGridPro.Destroy;
begin
  FPan.Free;
  inherited;
end;

procedure TDBGridPro.DoKeyUped(Sender: TObject; var Key: Word; Shift: TShiftState);
var
  cl : TColumn;
begin
  cl := Columns[SelectedIndex];
  case Key of
    VK_RETURN:
    begin
    {һColumnΪͣ
      1 ColumnİťΪԶ
      2 ColumnPickListǿգӦֶlookup}
    if (cl.ButtonStyle=cbsAuto) and ((cl.PickList.Count>0) or (cl.Field.FieldKind=fkLookup)) and (curCell.tag = 0) and not (ssShift in Shift) then
    begin
    {ѻسתAlt+µб}
      Key := 0;
      Shift := [ ];
      keybd_event(VK_MENU,0,0,0);
      keybd_event(VK_DOWN,0,0,0);
      keybd_event(VK_DOWN,0,KEYEVENTF_KEYUP,0);
      keybd_event(VK_MENU,0,KEYEVENTF_KEYUP,0);
      curCell.tag := 1;
      exit;
    end;
    {תTab}
    Key := 0;
    keybd_event(VK_TAB,0,0,0);
    keybd_event(VK_TAB,0,KEYEVENTF_KEYUP,0);
  end;
  VK_RIGHT :
  begin
  {ñ༭еֳ}
  i := GetWindowTextLength(InPlaceEditor.Handle);
  {ñ༭еĹλ}
  GetCaretPos(p);
  p.x := p.X + p.Y shr 16;
  j := SendMessage(InPlaceEditor.Handle,EM_CHARFROMPOS,0,p.X);
  if (i=j) then {ĩλ}
    begin
      Key := 0;
      keybd_event(VK_TAB,0,0,0);
      keybd_event(VK_TAB,0,KEYEVENTF_KEYUP,0);
    end;
  end;
  VK_LEFT:
  begin
    GetCaretPos(p);
    p.x := p.X + p.Y shr 16;
    if SendMessage(InPlaceEditor.Handle,EM_CHARFROMPOS,0,p.X)=0 then
    begin {λ}
      Key := 0;
      keybd_event(VK_SHIFT,0,0,0);
      keybd_event(VK_TAB,0,0,0);
      keybd_event(VK_TAB,0,KEYEVENTF_KEYUP,0);
      keybd_event(VK_SHIFT,0,KEYEVENTF_KEYUP,0);
    end;
  end;
  else begin {¼ûǷ޸}
    if (Columns[SelectedIndex].PickList.Count>0) and (curCell.tag = 0) then
      if SendMessage(InPlaceEditor.Handle,EM_GETMODIFY,0,0)=1 then
        curCell.tag := 1;
    end;
  end;
end;

procedure TDBGridPro.DoOwnDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if FOwnDraw=false then DefaultDrawColumnCell(Rect,DataCol,Column,State);
  if @OnOwnDrawColumnCell<>nil then OnOwnDrawColumnCell(Sender,Rect,DataCol, Column,State);
end;

procedure TDBGridPro.InPlaceEditorWndProcHook(var msg: TMessage);
var m : integer;
begin
  m := msg.Msg;
  {=inherited}
  hInplaceEditorWndProc(msg);
  {ǸıλúʹС¼ӿ}
  if m=WM_WINDOWPOSCHANGED then AddBox;
end;

procedure TDBGridPro.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited;
  DoKeyUped(Self,Key,Shift);
end;

end. 

{ϴWindows2000Delphi6ϲͨ} 

 
 2004-3-20 14:34:24    ӡ TDBGrid 

procedure PrintDbGrid(DataSet:TDataSet;DbGrid:TDbGrid;Title:String);
var
PointX,PointY:integer;
 ScreenX:integer;
 i,lx,ly:integer;
 px1,py1,px2,py2:integer;
 RowPerPage,RowPrinted:integer;
 ScaleX:Real;
 THeight:integer;
 TitleWidth:integer;
 SumWidth:integer;
 PageCount:integer;
 SpaceX,SpaceY:integer;
 RowCount:integer;
begin
PointX:=Round(GetDeviceCaps(printer.Handle,LOGPIXELSX)/2.54);
PointY:=Round(GetDeviceCaps(printer.Handle,LOGPIXELSY)/2.54);
 ScreenX:=Round(Screen.PixelsPerInch/2.54);
ScaleX:=PointX/ScreenX;
 RowPrinted:=0;
 SumWidth:=0;
 printer.BeginDoc;
 With Printer.Canvas do
 begin
  DataSet.DisableControls;
   DataSet.First ;
   THeight:=Round(TextHeight('')*1.5);//趨ÿи߶Ϊַߵ1.5
   SpaceY:= Round(TextHeight('')/4);
   SpaceX:=Round(TextWidth('')/4);
   RowPerpage:=Round((printer.PageHeight-5*PointY)/THeight); //±Ե2
   ly:=2*PointY;
   PageCount:=0;
  while not DataSet.Eof do
   begin
    if (RowPrinted=RowPerPage) or (RowPrinted=0) then
     begin
      if RowPrinted<>0 then
      Printer.NewPage;
       RowPrinted:=0;
       PageCount:=PageCount+1;
       Font.Name:='';
       Font.size:=16;
       Font.Style:=Font.Style+[fsBold];
       lx:=Round((Printer.PageWidth-TextWidth(Title))/2);
       ly:=2*PointY;
       TextOut(lx,ly,Title);
       Font.Size:=11;
       Font.Style:=Font.Style-[fsBold];
       lx:=Printer.PageWidth-5*PointX;
       ly:=Round(2*PointY+0.2*PointY);
       if RowPerPage*PageCount>DataSet.RecordCount then
        RowCount:=DataSet.RecordCount
       else
       RowCount:=RowPerPage*PageCount;
       TextOut(lx,ly,''+IntToStr(RowPerPage*(PageCount-1)+1)+'-'+IntToStr(RowCount)+''+IntToStr(DataSet.RecordCount)+'');
       lx:=2*PointX;
       ly:=ly+THeight*2;
       py1:=ly-SpaceY;
       if RowCount=DataSet.RecordCount then
        py2:=py1+THeight*(RowCount-RowPerPage*(PageCount-1)+1)
       else
        py2:=py1+THeight*(RowPerPage+1);
       SumWidth:=lx;
       for i:=0 to DBGrid.Columns.Count-1 do
       begin
       px1:=SumWidth-SpaceX;
         px2:=SumWidth;
         MoveTo(px1,py1);
         LineTo(px2,py2);
         TitleWidth:=TextWidth(DBGrid.Columns[i].Title.Caption);
         lx:=Round(SumWidth+(DBGrid.Columns[i].width*scaleX-titleWidth)/2);
         TextOut(lx,ly,DBGrid.Columns[i].Title.Caption);
         SumWidth:=Round(SumWidth+DBGrid.Columns[i].width*scaleX)+SpaceX*2;
       end;
       px1:=SumWidth;      //һ
       px2:=SumWidth;
       MoveTo(px1,py1);
       LineTo(px2,py2);
       px1:=2*PointX;            //һ
     px2:=SumWidth;
      py1:=ly-SpaceY;
      py2:=ly-SpaceY;
       MoveTo(px1,py1);
       LineTo(px2,py2);
       py1:=py1+THeight;
       py2:=py2+THeight;
       MoveTo(px1,py1);
       LineTo(px2,py2);
     end;
   lx:=2*PointX;
     ly:=ly+THeight;
     px1:=lx;
     px2:=SumWidth;
     py1:=ly-SpaceY+THeight;
     py2:=ly-SpaceY+THeight;
     MoveTo(px1,py1);
     LineTo(px2,py2);
     for i:=0 to DBGrid.Columns.Count-1 do
     begin
       TextOut(lx,ly,DataSet.FieldByname(DBGrid.Columns[i].Fieldname).AsString);
       lx:=Round(lx+DBGrid.Columns[i].width*ScaleX+SpaceX*2);
     end;
     RowPrinted:=RowPrinted+1;
     DataSet.next;
   end;
   DataSet.first;
   DataSet.EnableControls;
 end;
 printer.EndDoc;
end;


ӡStringGrid

Procedure TACDListerMain.PrintTable;
 Var
   margins: TRect;
   spacing: Integer;
   Cols: TList;
   Dlg: TPrintProgressDlg;

 Procedure SetColumnWidth;
   Var
     i, k, w: Integer;
   Begin
     Printer.Canvas.Font.Style := [ fsBold ];
     For i := 0 To Pred( Grid.ColCount ) Do

      Cols.Add( Pointer( Printer.Canvas.TextWidth( Grid.Cells[ i,0 ] )));

     Printer.Canvas.Font.Style := [];
     For i := 1 To Pred( Grid.RowCount ) Do
       For k := 0 To Pred( Grid.ColCount ) Do Begin
         w:= Printer.Canvas.TextWidth( Grid.Cells[ k, i ] );
         If w > Integer( Cols[ k ] ) Then
           Cols[ k ] := Pointer( w );
       End; { For }

     w := 2 * Printer.Canvas.Font.PixelsPerInch div 3;
     margins :=
       Rect( w, w, Printer.PageWidth-w, Printer.PageHeight - w );
     spacing := Printer.Canvas.Font.PixelsPerInch div 10;

     w := 0;
     For i := 0 To Pred(cols.Count) Do
       w := w + Integer( cols[ i ] ) + spacing;
     w := w - spacing;
     If w > (margins.right-margins.left ) Then Begin
       w := w - (margins.right-margins.left );
       cols[ cols.Count-2 ] :=
         Pointer( Integer( cols[ cols.Count-2 ] ) - w );
     End; { If }

     w:= 0;
     For i := 0 To Pred(cols.Count) Do
       w := w + Integer( cols[ i ] ) + spacing;
     margins.right := w - spacing + margins.left;
   End; { SetColumnWidth }

 Procedure DoPrint;
   Var
     i: Integer;
     y: Integer;
   Procedure DoLine(lineno: Integer);
     Var
       x, n: Integer;
       r: TRect;
       th: Integer;
     Begin
       If Length(Grid.Cells[0,lineno]) = 0 Then Exit;

       x:= margins.left;
       With Printer.Canvas Do Begin
         th := TextHeight( 'y' );
         For n := 0 To Pred( Cols.Count ) Do Begin
           r := Rect( 0, 0, Integer(Cols[ n ]), th);
           OffsetRect( r, x, y );
           TextRect( r, x, y, Grid.Cells[ n, lineno ] );
           x := r.right + spacing;
         End; { For }
       End; { With }
       y := y + th;
     End; { DoLine }
   Procedure DoHeader;
     Begin
       y:= margins.top;
       With Printer.Canvas Do Begin
         Font.Style := [ fsBold ];
         DoLine( 0 );
         Pen.Width := Font.PixelsPerInch div 72;
         Pen.Color := clBlack;
         MoveTo( margins.left, y );
         LineTo( margins.right, y );
         Inc( y, 2 * Pen.Width );
         Font.Style := [ ];
       End; { With }
     End; { DoHeader }
   Begin
     y:= 0;
     For i := 1 To Pred( Grid.RowCount ) Do Begin
       Dlg.Progress( i );
       Application.ProcessMessages;
       If FPrintAborted Then Exit;

       If y = 0 Then
         DoHeader;
       DoLine( i );
       If y >= margins.bottom Then Begin
         Printer.NewPage;
         y:= 0;
       End; { If }
     End; { For }
   End; { DoPrint }

 Begin
   FPrintAborted := False;
   Dlg := TPrintProgressDlg.Create( Application );
   With Dlg Do
   try
     OnAbort := PrintAborted;
     Display( cPrintPreparation );
     SetProgressRange( 0, Grid.RowCount );
     Show;
     Application.ProcessMessages;
     Printer.Orientation := poLandscape;

     Printer.BeginDoc;
     Cols:= Nil;
     try
       Cols:= TLIst.Create;
       Printer.Canvas.Font.Assign( Grid.Font );
       SetColumnWidth;
       Display( cPrintProceeding );
       Application.ProcessMessages;
       DoPrint;
     finally
       Cols.Free;
       If FPrintAborted Then
         Printer.Abort
       Else
         Printer.EndDoc;
     end;
   finally
     Close;
   End; { With }
 End; { TACDListerMain.PrintTable }
  

 
 2004-3-23 9:30:43    DELPHIAPIʵǶ 
--------------------------------------------------------------------------------

DelphiTDBGridһʮ鷳顣ҽһWIN32 APITDBGRIDǶCHECKBOXķ

TDBGridʾͱ༭ݿм¼ϢҪڳƹҪʹõһǿĹߡTDBGridкܶҪԣǿڳƽ׶κͳйнáTDBGridкܶҪԣصOptionԺDefaultDrawingԣԼ÷οļ

OptionsԣTDBGridһչԣڳƽ׶OptionsԿԿTDBGridʾԺͶ¼Ӧԡ

DefalultDrawingԣǲԣڿиԪĻƷʽȱʡ£ԵֵΪTrueҲ˵DelphiʹȱʡķиԪԪеݣԪеݸӦֶβDisplayFormatԺEidtFormatԽʾͻơDefaulDrawingԱΪFalseDelphiԶػиԪԪеݣûԼΪTDBGridOnDrawDataCell¼дӦĳڻƸԪеݡ

ҪעǣһֶεõʱTDBGrid.Optionsе gdEditingԲܱóΪɱ༭ģʽ⣬TDBGrid.DefaultDrawingԲҪΪFALSE򣬾ͲܵõлԵľ

ƿʼʱӦǣҪ趨һ洢ԭʼ TDBGrid.OptionsֵһbooleanֶõʱҪرTDBGrid.OptionsgdEditingĿɱ༭ģʽӦʧȥʱҪ»ָԭʼ TDBGrid.Optionsֵ

ʵпͨôոı䲼ֵҪTDBGrid.OnCellClick¼TDBGrid.OnKeyDown¼Ϊ¼Ǹı䵥Ԫ߼ֶεĲֵΪ˼ٴظôһ˽й̣SaveBoolean;߼ֵ룬Ժڲͬ¼еô˹̼ɡ

 TDBGrid.OnDrawColumnCell¼ĴĹؼǶʾĴͳǣڱʵȻλеԪλԽеԴﵽǶӾЧַȻеʵʱԺܲ߲õķǳWIN32 APIDrawFrameControl()ڴ˺ֱӻCheckboxԾڱʵʹAPIDrawFrameControl()Ǳڡ

TDBGrid.OnDrawColumnCell¼Уһע⵽趨һ鳣صֵ벼ֵһµģֶ߼ֶΣֻ䲼ֵУṩDrawFrameControl()е״̬еãӶʵCheckboxеǶЧ

Դ£

type

 TForm1 = class(TForm)
DataSource1: TDataSource;
Table1: TTable;
DBGrid1: TDBGrid;
procedure DBGrid1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
procedure DBGrid1ColEnter(Sender: TObject);
procedure DBGrid1ColExit(Sender: TObject);
procedure DBGrid1CellClick(Column: TColumn);
procedure DBGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
 private
{ Private declarations }
OriginalOptions : TDBGridOptions;
procedure SaveBoolean;
 public
{ Public declarations }
 end;

{...}

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject;
 const Rect: TRect; DataCol: Integer;
 Column: TColumn; State: TGridDrawState);
const
 // ֵղֵأ
 CtrlState : array[Boolean] of Integer = (DFCS_BUTTONCHECK,DFCS_BUTTONCHECK or DFCS_CHECKED);
begin
 //ȷֻ߼ֶβܲ
 if Column.Field.DataType = ftBoolean then
 begin
DBGrid1.Canvas.FillRect(Rect);
DrawFrameControl(DBGrid1.Canvas.Handle,
 Rect,
 DFC_BUTTON,
 CtrlState[Column.Field.AsBoolean]);
 end;
end;

procedure TForm1.DBGrid1ColEnter(Sender: TObject);
begin
 // ȷ߼ֶ
 if DBGrid1.SelectedField.DataType = ftBoolean then
 begin
OriginalOptions := DBGrid1.Options;
DBGrid1.Options := DBGrid1.Options - [dgEditing];
 end;
end;

procedure TForm1.DBGrid1ColExit(Sender: TObject);
begin
 //ȷ߼ֶ
 if DBGrid1.SelectedField.DataType = ftBoolean then
DBGrid1.Options := OriginalOptions;
end;

procedure TForm1.DBGrid1CellClick(Column: TColumn);
begin
 //ȷ߼ֶ
 if DBGrid1.SelectedField.DataType = ftBoolean then
SaveBoolean();
end;

procedure TForm1.DBGrid1KeyDown(Sender: TObject;
 var Key: Word; Shift: TShiftState);
begin
 //ȷ߼ֶκͿոڼбû
 if ( Key = VK_SPACE ) and
 ( DBGrid1.SelectedField.DataType = ftBoolean ) then
SaveBoolean();
end;

procedure TForm1.SaveBoolean;
begin
 DBGrid1.SelectedField.Dataset.Edit;
 DBGrid1.SelectedField.AsBoolean :=not DBGrid1.SelectedField.AsBoolean;
 DBGrid1.SelectedField.Dataset.Post;
end;

ԴPWIN+DELPHI5.0ֱͨá